新手学Python-SSH登录

python自动登录并执行命令:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# filename: pexpect_ssh.py
'''
Created on 2015-12-10

@author: LC
'''
import pexpect

if __name__ == '__main__':
    user = 'admin'
    ip = '192.168.0.1'
    mypassword = 'password'

    print user
    child = pexpect.spawn('ssh %s@%s' % (user,ip))
    child.expect ('password:')
    child.sendline (mypassword)

    child.expect('$')
    child.sendline('sudo -s')
    child.expect (':')
    child.sendline (mypassword)
    child.expect('#')
    child.sendline('ls -la')
    child.expect('#')
    print child.before   # Print the result of the ls command.
    child.sendline("echo '112' >> /home/lc/1.txt ")
    child.interact()     # Give control of the child to the user.

    pass

 

我们ssh远程登录的时候,首先输入ssh username@ipaddress,第一次登录的时候系统会提示是否需要继续连接。如果是,我们需要输入yes,然后等一段时间提示我们输入密码,这时候再输入密码。之后我们就登录成功,能够执行命令了。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pexpect

def ssh_cmd(ipaddress, passwd, cmd):
    ret = -1
    ssh = pexpect.spawn('ssh root@%s "%s"' % (ipaddress, cmd))
    try:
        i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5)
        if i == 0 :
            ssh.sendline(passwd)
        elif i == 1:
            ssh.sendline('yes\n')
            ssh.expect('password: ')
            ssh.sendline(passwd)
        ssh.sendline(cmd)
        r = ssh.read()
        print r
        ret = 0
    except pexpect.EOF:
        print "EOF"
        ssh.close()
        ret = -1
    except pexpect.TIMEOUT:
        print "TIMEOUT"
        ssh.close()
        ret = -2
    return ret

ssh_cmd("192.168.0.1", "ppppassword", "dir") # execute the ssh_cmd function

 

这个对于现在的我来说很有用,呵呵

利用pexpect还可以做telnet、ftp、ssh、scp等的自动登录。

 

 

Thursday, December 10, 2015 | Python

文章评论

No comments posted yet.

发表评论

Please add 7 and 7 and type the answer here: