2015年8月27日 07:20 by wst
python小技巧由于公司的服务器只能通过publickey登录,本地只有一个dsa文件,登录服务器时必须通过此文件,下面具体给出示例;
1,打开ssh客户端,然后执行命令
import paramiko
def ssh2(ip,username,passwd,cmd):
try:
paramiko.util.log_to_file('paramiko.log')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
keyFile = r'E:\workfile\mylib\id_dsa_2048'
ssh.connect(ip,22,username,passwd,timeout=5,key_filename=keyFile)
stdout,stdin,stderr = ssh.exec_command(cmd)
print stdout._read(1024)
except Exception,e :
print "Error.",e
if __name__ == "__main__":
cmd = "mkdir -p ./aa/bb/cc"
ssh2('192.168.0.3','root','*********','ls')
2,打开sftp客户端,然后上传文件
#!/usr/bin/env python
import socket
import paramiko
import os
username='root'
hostname='192.168.0.3'
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()
privatekeyfile = os.path.expanduser(r'E:\workfile\mylib\id_dsa_2048')
mykey = paramiko.DSSKey.from_private_key_file(privatekeyfile,password='********')
t.auth_publickey(username,mykey)
sftp=paramiko.SFTPClient.from_transport(t)
sftp.put(r"E:\workfile\test\crm.rar","/root/crm.rar")
sftp.close()
t.close()
3,综合使用
import paramiko
def ssh2(ip,username,passwd,cmd):
try:
paramiko.util.log_to_file('paramiko.log')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
keyFile = r'E:\workfile\mylib\id_dsa_2048'
ssh.connect(ip,22,username,passwd,timeout=5,key_filename=keyFile)
stdout,stdin,stderr = ssh.exec_command(cmd)
print stdout._read(1024)
sftp = ssh.open_sftp()
sftp.put(r"E:\workfile\test\crm.rar","/root/crm.rar")
ssh.close()
except Exception,e :
print "Error.",e
if __name__ == "__main__":
cmd = "mkdir -p ./aa/bb/cc"
ssh2('192.168.0.3','root','********','ls')