paramiko 不通过密钥文件登陆,这很好解决,直接connect输入用户名和密码就ok
# -*- coding: utf-8 -*-
import paramiko
paramiko.util.log_to_file('paramiko.log') #记录日志文件
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('127.0.0.1',username = 'root',password='******')
cmd = 'cd' #进入用户目录home
stdin,stdout,stderr = ssh.exec_command(cmd)
print stdout.readlines()
cmd = 'ls >test' #管道,ls命名的输出到文件test里面
stdin,stdout,stderr = ssh.exec_command(cmd)
print stdout.readlines()
cmd = 'cat test' # 显示test的内容,即ls命名的结果
stdin,stdout,stderr = ssh.exec_command(cmd)
#print stdout.readlines() #结果 汉字用的字符显示
通过以上方式可以实现。
在需要密匙文件时,paramiko 则需要通过如下方式登陆:
# -*- coding: utf-8 -*-
import paramiko
pkey='E:/wamp/www/tools/id_rsa' #本地密钥文件路径[此文件服务器上~/.ssh/id_rsa可下载到本地]
key=paramiko.RSAKey.from_private_key_file(pkey,password='******') #有解密密码时,
paramiko.util.log_to_file('paramiko.log')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #通过公共方式进行认证 (不需要在known_hosts 文件中存在)
#ssh.load_system_host_keys() #如通过known_hosts 方式进行认证可以用这个,如果known_hosts 文件未定义还需要定义 known_hosts
ssh.connect('127.0.0.1',username = 'root',password='******',pkey=key) #这里要 pkey passwordkey 密钥文件
stdin,stdout,stderr=ssh.exec_command('hostname')
print stdout.read()
stdin,stdout,stderr=ssh.exec_command('ls')
print stdout.read()
通过sftp方式进行文件传输:
# -*- coding: utf-8 -*-
import paramiko
import os
pkey='E:/wamp/www/tools/id_rsa'
key=paramiko.RSAKey.from_private_key_file(pkey,password='******')
paramiko.util.log_to_file('paramiko.log')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('127.0.0.1',username = 'root',password='******',pkey=key)
t = ssh.get_transport()
sftp=paramiko.SFTPClient.from_transport(t)
d = sftp.put("mm.txt","/home/www/mm.txt")
print d
t.close()
通过sftp方式进行文件下载:
# -*- coding: utf-8 -*-
import paramiko
import os
pkey='E:/wamp/www/tools/id_rsa'
key=paramiko.RSAKey.from_private_key_file(pkey,password='******')
paramiko.util.log_to_file('paramiko.log')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('127.0.0.1',username = 'root',password='******',pkey=key)
t = ssh.get_transport()
sftp=paramiko.SFTPClient.from_transport(t)
d = sftp.get("/home/www/mm.txt","mm.txt")
print d
t.close()
参考文档:
http://5ydycm.blog.51cto.com/115934/340854/ [paramiko ssh sftp ] *****
http://blog.chinaunix.net/uid-25979788-id-2203623.html [使用python通过SSH登陆linux并操作 无密钥]
http://hi.baidu.com/397090770/item/c79c7c960afad3dc1b49dfae (putty 生成【私人】密钥的方式,可进行研究)
http://www.cnblogs.com/gannan/archive/2012/02/06/2339883.html (paramiko的安装与使用)
http://www.pyshell.com/index.php/archives/329 (Paramiko模块系列之二:利用密匙无密码登陆远程服务器) ******
[之一:paramiko模块系列之一:模拟ssh登录远程服务器]
[之二:paramiko模块系列之二:利用密匙无密码登陆远程服务器]
[之三:paramiko模块系列之三:批量上传文件] http://www.pyshell.com/index.php/archives/332
[之四:paramiko模块系列之三:批量下载文件至本地] http://www.pyshell.com/index.php/archives/337