如何使用Paramiko访问远程主机?

Pat*_*Pat 2 python ssh paramiko

我刚刚开始使用Paramiko连接到另一台主机.我可以通过其本地网络中的内部IP地址访问此主机,这样可以正常工作(无论是在Python中还是ssh在控制台中).

但是,当我尝试通过其外部IP地址访问主机时,通过Paramiko的访问ssh在控制台仍然有效时失败.这里唯一的区别是,我使用机器的外部IP地址而不是主机的内部IP地址.

有人可以帮忙吗?可能是Paramiko与我在路由器上配置的端口转发有什么冲突吗?

到目前为止,这是我的代码:

import paramiko

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

target_host = 'external.IP'
# target_host = 'internal.IP'

# Internal access port for ssh transfer.
# target_port = 22

# External access port for ssh transfer.
target_port = ABCD

pwd = 'my.password'
un = 'my.username'

ssh.connect( hostname = target_host , username = un, password = pwd )

stdin, stdout, stderr = ssh.exec_command('ls -1 .')

print "STDOUT:\n%s\n\nSTDERR:\n%s\n" %( stdout.read(), stderr.read() )
Run Code Online (Sandbox Code Playgroud)

添加:

收到的完整错误消息是:

回溯(最近一次调用最后一次):文件"./test.py",第25行,在ssh.connect中(hostname = target_host,username = un,password = pwd)文件"/usr/local/lib/python2.7/ site-packages/paramiko/client.py",第251行,在连接retry_on_signal(lambda:sock.connect(addr))文件"/usr/local/lib/python2.7/site-packages/paramiko/util.py" ,第270行,在retry_on_signal中返回函数()文件"/usr/local/lib/python2.7/site-packages/paramiko/client.py",第251行,在retry_on_signal(lambda:sock.connect(addr))文件"/usr/local/Cellar/python/2.7.9/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py",第224行,在meth return getattr(self._sock,name)(*args)socket.error:[Errno 61]连接被拒绝

Python和控制台访问之间的唯一区别是端口.可能是Paramiko总是通过端口22进入ssh吗?如果是这样,有没有办法指示Paramiko通过另一个港口?

Val*_*yov 6

我的主机上的脚本输出有这个改变:stdin,stdout,stderr = ssh.exec_command('ls -1/root | head -n 5')

1.py

import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
target_host = '127.0.0.1'
target_port = 22
target_port = 22
pwd = 'password'
un = 'root'
ssh.connect( hostname = target_host , username = un, password = pwd )
stdin, stdout, stderr = ssh.exec_command('ls -1 /root|head -n 5')
print "STDOUT:\n%s\n\nSTDERR:\n%s\n" %( stdout.read(), stderr.read() )
# For Python3
# print("STDOUT:\n%s\n\nSTDERR:\n%s\n" %( stdout.read(), stderr.read() )) 
Run Code Online (Sandbox Code Playgroud)

python 1.py

STDOUT:
~
1
1421750672-TWya15.png
1.py
7


STDERR:
Run Code Online (Sandbox Code Playgroud)

我认为你需要ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())避免

The authenticity of host 'localhost (::1)' can't be
established.
RSA key fingerprint is 
22:fb:16:3c:24:7f:60:99:4f:f4:57:d6:d1:09:9e:28.
Are you sure you want to continue connecting 
(yes/no)? 

import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(
    paramiko.AutoAddPolicy())
ssh.connect('127.0.0.1', username='jesse', 
    password='lol')
Run Code Online (Sandbox Code Playgroud)

使用PARAMIKO进行SSH编程| 完全不同