python使用paramiko模块实现ssh远程命令执行,与sftp文件下载功能,其余方法查看API:
#-*- coding: utf-8 -*-
#!/usr/bin/python
import paramiko
def ssh2(ip, username, passwd, cmd, port=6802):
try:
# 创建ssh实例
ssh = paramiko.SSHClient()
# 设置策略
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 进行连接
ssh.connect(ip, port, username, passwd, timeout=5)
for m in cmd:
# 返回输出结果
stdin, stdout, stderr = ssh.exec_command(m)
# stdin.write("Y") #简单交互,输入 ‘Y’
out = stdout.readlines()
# 屏幕输出
for o in out:
print o,
print '%s\tOK\n' % (ip)
ssh.close()
except Exception,e:
print '%s\tError\n' % (ip)
print e.message
def ssh_getfile(ip, username, passwd, remotepath, localpath, port=6802):
# 创建传输实例
t = paramiko.Transport((ip ,port))
#创建scoket
t.connect(None,username, passwd)
#创建sftp
sftp = paramiko.SFTPClient.from_transport(t)
#下载文件
sftp.get(remotepath, localpath)
t.close()
if __name__ == '__main__':
cmd=['/usr/bin/python /opt/ding/get_aaa_file.py']
ssh2('182.106.XX.XX','user','passwd',cmd)
ssh_getfile('182.106.XX.2','user','passwd','/home/liu/aaa.txt','/home/liu/aaa.txt',22)