ssh自动登录并执行指令

1、使用paramiko库实现

示例代码如下(loginUsePwdTest1):

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

import warnings

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    import paramiko

hostname='192.168.1.100'
username='root'
password='123456'

#paramiko.util.log_to_file('paramiko.log')
s=paramiko.SSHClient()
#s.load_system_host_keys()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(hostname = hostname,username=username, password=password)
stdin,stdout,stderr=s.exec_command('ifconfig;free;df -h')
print stdout.read()
s.close()
raw_input()

该代码的github地址: https://github.com/mike-zhang/pyExamples/blob/master/sshTools/loginUsePwdTest1.py

2、使用pexpect借助ssh命令实现

示例代码如下(knn_sklearn_test1.py):

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

import pexpect
from getpass import getpass

#passwd = getpass()
passwd = "123456"

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

if __name__ == '__main__':
    ssh_cmd("root","192.168.1.100","ifconfig")

该代码的github地址:

https://github.com/mike-zhang/pyExamples/blob/master/sshTools/loginUsePwdTest2.py