一般使用paramiko的功能就是通过ssh远程执行命令,远程传输文件等等。
模拟远程执行命令:
import paramiko
#设置日志记录
paramiko.util.log_to_file('/tmp/test')
#建立连接
ssh=paramiko.SSHClient()
#缺失host_knows时的处理方法
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#连接远程客户机器
ssh.connect('10.1.6.190',port=22,username='root',password='password',compress=True)
#获取远程命令执行结果
stdin, stdout, stderr = ssh.exec_command('hostname;uptime')
print stdout.read()
如果有交互 用stdin。write()
(1)sudo后要加-S,表示从stdin接收密码;
(2)stdin.write(‘password\n')最后要加\n作为命令的结束,否则服务器一直等待;
(3) flush()写入的缓冲( flush() any buffer you're writing to )
stdin, stdout, stderr = ssh.exec_command('sudo -S ls')
stdin.write('password\n')
stdin.flush()
#输出执行结果
ssh.close()
执行结果如下:
模拟远程文件传输:
import paramiko
#建立一个加密的管道
scp=paramiko.Transport(('10.1.6.190',22))
#建立连接
scp.connect(username='root',password='password')
#建立一个sftp客户端对象,通过ssh transport操作远程文件
sftp=paramiko.SFTPClient.from_transport(scp)
#Copy a remote file (remotepath) from the SFTP server to the local host
sftp.get('/root/debian7','/tmp/debian7')
#Copy a local file (localpath) to the SFTP server as remotepath
sftp.put('/root/crash-6.1.6.tar.gz','/tmp/crash-6.1.6.tar.gz')
scp.close()
invoke_shell to establih a interactive session
build a ssh connection
remoteconn =ssh.invoke_shell()
output = remoteconn.recv(1000)
print output
# initiate SSH connection
remote_conn_pre.connect(ip, username=username, password=password, look_for_keys=False, allow_agent=False)
print "SSH connection established to %s" % ip
# Use invoke_shell to establish an 'interactive session'
remote_conn = remote_conn_pre.invoke_shell()
print "Interactive SSH session established"
# Strip the initial router prompt
output = remote_conn.recv(1000)
# See what we have
print output
# Turn off paging
disable_paging(remote_conn)
# Now let's try to send the router a command
remote_conn.send("\n")
remote_conn.send("show ip int brief\n")
# Wait for the command to complete
time.sleep(2)
output = remote_conn.recv(5000)
print output
执行结果如下:
可以利用多进程或线程可以批量执行命令:
import paramiko
import threading
def ssh_cmd(ip,port,username,passwd,cmd):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,passwd)
for m in cmd:
stdin, stdout, stderr = ssh.exec_command(m)
print(stdout.readlines())
ssh.close()
if __name__=='__main__':
cmd = ['ls','ifconfig']
a=threading.Thread(target=ssh_cmd,args=(ip,port,username,passwd,cmd))
a.start()
a.join()