我正在运行来自paramiko github的demo文件夹中的demo_sftp.py文件。我在PyDev中逐步执行它,并期望会出现错误,因为我没有连接到服务器所需的密钥,但是我得到了一条打印语句,说明脚本无法打开主机密钥文件,然后继续进行get和put操作。
以下是代码片段。
以下是代码片段。
try:
host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
except IOError:
try:
# try ~/ssh/ too, because windows can't have a folder named ~/.ssh/
host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts'))
except IOError:
print '*** Unable to open host keys file'
host_keys = {}
if host_keys.has_key(hostname):
hostkeytype = host_keys[hostname].keys()[0]
hostkey = host_keys[hostname][hostkeytype]
print 'Using host key of type %s' % hostkeytype
# now, connect and use paramiko Transport to negotiate SSH2 across the connection
try:
t = paramiko.Transport((hostname, port))
t.connect(username=username, password=password, hostkey=hostkey)
sftp = paramiko.SFTPClient.from_transport(t)
# dirlist on remote host
dirlist = sftp.listdir('.')
print "Dirlist:", dirlist
我本来希望在t.connect行出现异常,因为hostkey是NoneType。
当我使用ssh进行连接时
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect('.'.join([self.name, self.domain]),
username=self.username, password=self.password)
stdin, stdout, stderr = ssh.exec_command("ps aux | grep Xvnc | wc -l")
我必须有AutoAddPolicy()这行,否则它就会失败。那么有什么区别呢?显然,我只是在学习这个,但我认为sftp应该和ssh一样严格。