Home Backend Development Python Tutorial python远程登录代码

python远程登录代码

Jun 16, 2016 am 08:47 AM
python Remote login

在 python 中有一个 telnetlib,它的作用就是建立一个通到主机的 telnet连线实体, 然后向主机传送命令 (就像用键盘输入一样 )并从该连线接收数据。利用它, 我们可以把示范 1的所有内容从 "人 -机 '交流变成'机 -机 '交流,这样也可以做到处理 pop3 邮箱的工作。不过既然我们已经试过了 pop3,这一次可以试用真的 telnet 埠 23 做些好玩的东西。

 

 以下是代码片段:   1 # telnetdo.py     2 #!/usr/bin/env python     3      4 def telnetdo(HOST=None, USER=None, PASS=None, COMMAND=None):  #定义一个函数, 这将要用它会很容易      5   import telnetlib, sys     6      7   if   not   HOST:                           #如果没有给出所要的资料,则要求用户输入                      8      try:     9         HOST   = sys.argv[1]                 #记得吧, 序列是从 0开始数的,而sys.argv[0]会是你程式的名字     10         USER   = sys.argv[2]    11         PASS   = sys.argv[3]    12         COMMAND   = sys.argv[4]    13      except:    14         print   "Usage: telnetdo.py host user pass 'command'"    15         return    16     17   msg   = ['Debug   mesages:\n']             #这个用来存起所有从主机传回的讯息, 作除错时很有用     18     19   tn   = telnetlib.Telnet()                  #准备一个 telnet 连线的实体     20   try:    21      tn.open(HOST)                           #连接端绑定到主机 HOST  去     22   except:    23      print   "Cannot open host"    24      return    25     26   msg.append(tn.expect(['login:'],5))        #等待主机传回含有 'login:'字符的讯息,等候时限为 5秒     27   tn.write(USER+'\n')                        #向主机送出字串 USER   + '\n',如 USER  是    28                                              # 'pcheung' 则等于 'pcheung\n'    29   if   PASS:                                 #就像是在键盘打入一样。     30      msg.append(tn.expect(['Password:'],5))  #如果有 password  要打的话就送出密码字串,     31      tn.write(PASS+'\n')                     #但首先要等主机传回含有 'Password:'字样的讯息     32     33   msg.append(tn.expect([USER],5))            #因为通常登入后主机会显示出登入者名称,我们在主机回应中找这     34                                              #样的字符,如有的话则代表登入成功了     35   tn.write(COMMAND+'\n')                     #向主机发出指令     36   msg.append(tn.expect(['%'],5))             #等 5秒,如果程式完成了一般我们会收到     37                                              # shell prompt  吧,假设为 '%'    38   tn.close()                                 #关闭连线     39   del   tn    40   return   msg[len(msg)-1][2]                #把收到的讯息通通传回去。     41                                              #(注意 msg  中第 2个元素才是真的讯息,     42                                              #其他是附加资讯。     43     44 if __name__   == '__main__'                  #这是 python  常用的技巧:如果 telnetdo.py 程式    45                                              #是从 command prompt    46                                              #引发的话则 __name__  的内容为 __main__,相反    47                                              #如果是从别的程式用 import telnetdo  的话则    48                                              # __name__  会变成 'telnetdo'    49   print   telnetdo()                         #这样写的好处是从此 telnetdo  会成为你的扩展    50                                              #模组,你可以在别的程式中     51                                               #用telnetdo.telnetdo(HOST,USER,PASS,COMMAND)来调用它!
这个程式用法如下:

 

以下是代码片段:> chmod +x telnetdo.py  > telnetdo.py 'somehost' 'glace' 'xxxxxx' 'ls   -lF'    (0, , '\015\012\015\012Linux  (somehost)\015\012\015\015\012\015login: ')  (0, , 'Password:')  (0, , '\015\012Yup Release 2.6   somehost\015\012Last login: Wed   Mar    6 18:21:01 GMT 2002 by  UNKNOWN@xxx.xxx.xxx.xxxyou have   mail\015\012somehost:glace%')    total 320  -rw-r--r--    1 glace    user        139788 Feb    8 17:54 PQR2.1.txt  drwxr-xr-x    3 glace    user          4096 Feb   10 16:45 mytts/  drwxr-xr-x    3 glace    user          4096 Jan   29 19:03 sample/  drwxr-xr-x    2 glace    user          4096 Jan    6 16:38 tex/  drwxr-xr-x    2 glace    user          4096 Sep    5  2001 tmp/  drwxr-xr-x    2 glace    user            29 Feb   23  2001 tools/  drwxr-xr-x    2 glace    user            26 Feb    6 18:43 trash/  somehost:glace%  可以看到执行的结果和一些附加的资讯。这就是远端执行程式了。就算没有 rsh,照用可也。 哈,很方便吧。不过你应该留意到了程式执行时只等候了 5秒,就是说如果你要向主机发出像 'find . -name xxx   -print' 这样的命令应该等不到执行完这个 telnet session 就会被关闭了。不过仔细想一下,这要紧吗?我们现在所能做到的和真正人手 telnet 的差别并不大,想一想你会怎样解决长时间执行的问题?没错,就是 'nohup'和背景作业了。 就是说只要把程式呼叫改成:  telnetdo.py 'apocal' 'pcheung' 'xxxxxx' 'nohup   myprogram_or_script&'  就行了。如此一来,就算对方主机的 shell prompt 是 '>'或是 '>>>'都没有关系了。

(注意安全性并非是这类范例程式的着重点, 因此并不建议在实际工作中用它.) 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

How to use mysql after installation How to use mysql after installation Apr 08, 2025 am 11:48 AM

The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

HadiDB: A lightweight, horizontally scalable database in Python HadiDB: A lightweight, horizontally scalable database in Python Apr 08, 2025 pm 06:12 PM

HadiDB: A lightweight, high-level scalable Python database HadiDB (hadidb) is a lightweight database written in Python, with a high level of scalability. Install HadiDB using pip installation: pipinstallhadidb User Management Create user: createuser() method to create a new user. The authentication() method authenticates the user's identity. fromhadidb.operationimportuseruser_obj=user("admin","admin")user_obj.

Does mysql need the internet Does mysql need the internet Apr 08, 2025 pm 02:18 PM

MySQL can run without network connections for basic data storage and management. However, network connection is required for interaction with other systems, remote access, or using advanced features such as replication and clustering. Additionally, security measures (such as firewalls), performance optimization (choose the right network connection), and data backup are critical to connecting to the Internet.

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

Can mysql workbench connect to mariadb Can mysql workbench connect to mariadb Apr 08, 2025 pm 02:33 PM

MySQL Workbench can connect to MariaDB, provided that the configuration is correct. First select "MariaDB" as the connector type. In the connection configuration, set HOST, PORT, USER, PASSWORD, and DATABASE correctly. When testing the connection, check that the MariaDB service is started, whether the username and password are correct, whether the port number is correct, whether the firewall allows connections, and whether the database exists. In advanced usage, use connection pooling technology to optimize performance. Common errors include insufficient permissions, network connection problems, etc. When debugging errors, carefully analyze error information and use debugging tools. Optimizing network configuration can improve performance

How to solve mysql cannot connect to local host How to solve mysql cannot connect to local host Apr 08, 2025 pm 02:24 PM

The MySQL connection may be due to the following reasons: MySQL service is not started, the firewall intercepts the connection, the port number is incorrect, the user name or password is incorrect, the listening address in my.cnf is improperly configured, etc. The troubleshooting steps include: 1. Check whether the MySQL service is running; 2. Adjust the firewall settings to allow MySQL to listen to port 3306; 3. Confirm that the port number is consistent with the actual port number; 4. Check whether the user name and password are correct; 5. Make sure the bind-address settings in my.cnf are correct.

See all articles