我已验证的示例:
def paramiko_ssh(): host = "123.56.14.5" port = 22 client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.client.WarningPolicy()) try: client.connect(host, port, username='root', password='xxx', timeout=30) except Exception as e: print(e) stdin, stdout, stderr = client.exec_command('ls /opt') for line in stdout: print('... ' + line.strip('\n')) client.close() def paramiko_key(): try: k = paramiko.RSAKey.from_private_key_file("~/.ssh/id_rsa") client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname="123.56.14.5", username="root", pkey=k) stdin, stdout, stderr = client.exec_command('ls /opt') for line in stdout: print('... ' + line.strip('\n')) except Exception as e: print(e) finally: client.close()
pexpect代码示例
#!/usr/bin/python
# encoding=utf-8
# Filename: pexpect_test.py
import pexpect
defsshCmd(ip, passwd, cmd):
ret = -1
ssh = pexpect.spawn('ssh root@%s "%s"' % (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\n')
ssh.expect('password:')
ssh.sendline(passwd)
ssh.sendline(cmd)
r = ssh.read()
print r
ret = 0
except pexpect.EOF:
print "EOF"
ret = -1
except pexpect.TIMEOUT:
print "TIMEOUT"
ret = -2
finally:
ssh.close()
return ret
sshCmd('xxx.xxx.xxx.xxx','xxxxxx','ls /root')
paramiko代码示例
注意:必须要增加client.load_system_host_keys()此句,否则报如下错误:
unbound method missing_host_key() must be called with AutoAddPolicy instance as first argument (got SSHClient instance instead)
#!/usr/bin/python
# encoding=utf-8
# Filename: paramiko_test.py
import datetime
import threading
import paramiko
defsshCmd(ip, username, passwd, cmds):
try:
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
client.connect(ip, 22, username, passwd, timeout=5)
for cmd in cmds:
stdin, stdout, stderr = client.exec_command(cmd)
lines = stdout.readlines()
# print out
for line in lines:
print line,
print '%s\t 运行完毕\r\n' % (ip)
except Exception, e:
print '%s\t 运行失败,失败原因\r\n%s' % (ip, e)
finally:
client.close()
#上传文件
defuploadFile(ip,username,passwd):
try:
t=paramiko.Transport((ip,22))
t.connect(username=username,password=passwd)
sftp=paramiko.SFTPClient.from_transport(t)
remotepath='/root/main.py'
localpath='/home/data/javawork/pythontest/src/main.py'
sftp.put(localpath,remotepath)
print '上传文件成功'
except Exception, e:
print '%s\t 运行失败,失败原因\r\n%s' % (ip, e)
finally:
t.close()
#下载文件
defdownloadFile(ip,username,passwd):
try:
t=paramiko.Transport((ip,22))
t.connect(username=username,password=passwd)
sftp=paramiko.SFTPClient.from_transport(t)
remotepath='/root/storm-0.9.0.1.zip'
localpath='/home/data/javawork/pythontest/storm.zip'
sftp.get(remotepath,localpath)
print '下载文件成功'
except Exception, e:
print '%s\t 运行失败,失败原因\r\n%s' % (ip, e)
finally:
t.close()
if __name__ == '__main__':
# 需要执行的命令列表
cmds = ['ls /root', 'ifconfig']
# 需要进行远程监控的服务器列表
servers = ['xxx.xxx.xxx.xxx']
username = "root"
passwd = "xxxxxx"
threads = []
print "程序开始运行%s" % datetime.datetime.now()
# 每一台服务器创建一个线程处理
for server in servers:
th = threading.Thread(target=sshCmd, args=(server, username, passwd, cmds))
th.start()
threads.append(th)
# 等待线程运行完毕
for th in threads:
th.join()
print "程序结束运行%s" % datetime.datetime.now()
#测试文件的上传与下载
uploadFile(servers[0],username,passwd)
downloadFile(servers[0],username,passwd)
Secure File Transfer Using SFTPClient
SFTPClient is used to open an sftp session across an open ssh Transport and do remote file operations.
An SSH Transport attaches to a stream (usually a socket), negotiates an encrypted session, authenticates, and then creates stream tunnels, called Channels, across the session. Multiple channels can be multiplexed across a single session (and often are, in the case of port forwardings).
以下是用密码认证功能登录的
#!/usr/bin/env python
import paramiko
socks=('127.0.0.1',22)
testssh=paramiko.Transport(socks)
testssh.connect(username='root',password='000000')
sftptest=paramiko.SFTPClient.from_transport(testssh)
remotepath="/tmp/a.log"
localpath="/tmp/c.log"
sftptest.put(remotepath,localpath)
sftptest.close()
testssh.close()
以下是用DSA认证登录的(PubkeyAuthentication)
#!/usr/bin/env python
import paramiko
serverHost = "192.168.1.172"
serverPort = 22
userName = "root"
keyFile = "/root/.ssh/zhuzhengjun"
known_host = "/root/.ssh/known_hosts"
channel = paramiko.SSHClient();
#host_keys = channel.load_system_host_keys(known_host)
channel.set_missing_host_key_policy(paramiko.AutoAddPolicy())
channel.connect(serverHost, serverPort,username=userName, key_filename=keyFile )
testssh=paramiko.Transport((serverHost,serverPort))
mykey = paramiko.DSSKey.from_private_key_file(keyFile,password='xyxyxy')
testssh.connect(username=userName,pkey=mykey)
sftptest=paramiko.SFTPClient.from_transport(testssh)
filepath='/tmp/e.log'
localpath='/tmp/a.log'
sftptest.put(localpath,filepath)
sftptest.close()
testssh.close()
以下是用RSA Key认证登录的
#!/usr/bin/evn python
import os
import paramiko
host='127.0.0.1'
port=22
testssh=paramiko.Transport((host,port))
privatekeyfile = os.path.expanduser('~/.ssh/badboy')
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile,password='000000')
username = 'root'
testssh.connect(username=username, pkey=mykey)
sftptest=paramiko.SFTPClient.from_transport(testssh)
filepath='/tmp/e.log'
localpath='/tmp/a.log'
sftptest.put(localpath,filepath)
sftptest.close()
testssh.close()
另一种方法:
在paramiko中使用用户名和密码通过sftp传输文件,不使用key文件。
import getpass
import select
import socket
import traceback
import paramiko
def putfile():
#import interactive
# setup logging
paramiko.util.log_to_file('demo.log')
username = username
hostname = hostname
port = 22
# now connect
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((hostname, port))
except Exception, e:
print '*** Connect failed: ' + str(e)
traceback.print_exc()
sys.exit(1)
t = paramiko.Transport(sock)
try:
t.start_client()
except paramiko.SSHException:
print '*** SSH negotiation failed.'
sys.exit(1)
keys = {}
# check server's host key -- this is important.
key = t.get_remote_server_key()
# get username
t.auth_password(username, password)
sftp = paramiko.SFTPClient.from_transport(t)
# dirlist on remote host
d=datetime.date.today()-datetime.timedelta(1)
sftp.put(localFile,serverFile)
sftp.close()
t.close()
使用DSA认证登录的(PubkeyAuthentication)
#!/usr/bin/env python
import socket
import paramiko
import os
username='root'
hostname='192.168.1.169'
port = 22
sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((hostname, port))
t=paramiko.Transport(sock)
t.start_client()
key=t.get_remote_server_key()
#t.auth_password(username,'000000')
privatekeyfile = os.path.expanduser('/root/.ssh/zhuzhengjun')
mykey=paramiko.DSSKey.from_private_key_file(privatekeyfile,password='061128')
t.auth_publickey(username,mykey)
sftp=paramiko.SFTPClient.from_transport(t)
sftp.put("/tmp/a.log","/tmp/h.log")
sftp.close()
t.close()
使用RSA Key验证
#!/usr/bin/env python
import socket
import paramiko
import os
username='root'
hostname='127.0.0.1'
port = 22
sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((hostname, port))
t=paramiko.Transport(sock)
t.start_client()
key=t.get_remote_server_key()
#t.auth_password(username,'000000')
privatekeyfile = os.path.expanduser('~/.ssh/badboy')
mykey=paramiko.RSAKey.from_private_key_file(privatekeyfile,password='000000')
t.auth_publickey(username,mykey)
sftp=paramiko.SFTPClient.from_transport(t)
sftp.put("/tmp/a.log","/tmp/h.log")
sftp.close()
t.close()