Python编程
基于paramiko单用户名方式建立ssh连接
基于Python来建立ssh连接时,想必大家都会用paramiko库,具体连接时,通常会基于用户名+密码的方式进行连接,以下就是一个简单的例子。
>>>import paramiko
>>>client = paramiko.SSHClient()
>>>client.load_system_host_keys()
>>>client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
>>>client.connect('192.168.255.1',username='user', password='password', allow_agent=False)
但有时会遇到登录时只有用户名没有密码的情况,这个时候paramiko就会报错, 如下图所示。
>>> import paramiko
>>> ssh = paramiko.SSHClient()
>>> ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
>>> ssh.connect("192.168.255.1", username="root", allow_agent=False)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/pymodules/python2.6/paramiko/client.py", line 327, in connect
self._auth(username, password, pkey, key_filenames, allow_agent, look_for_keys)
File "/usr/lib/pymodules/python2.6/paramiko/client.py", line 481, in _auth
raise saved_exception
paramiko.AuthenticationException: Authentication failed.
后来搜索到StackOverflow上的一篇文章,说paramiko默认不支持单用户名的方式,paramiko库的client.py的_auth方法相关代码如下。
if password is not None:
try:
self._transport.auth_password(username, password)
return
except SSHException as e:
saved_exception = e
elif two_factor:
try:
self._transport.auth_interactive_dumb(username)
return
except SSHException as e:
saved_exception = e
# if we got an auth-failed exception earlier, re-raise it
if saved_exception is not None:
raise saved_exception
raise SSHException('No authentication methods available')
为了支持单用户名方式,需要做如下修改。
if password is not None:
try:
self._transport.auth_password(username, password)
return
except SSHException as e:
saved_exception = e
# modified to support only username is required
elif username is not None:
try:
self._transport.auth_none(username)
return
except SSHException as e:
saved_exception = e
elif two_factor:
raise SSHException('Two-factor authentication requires a password')
# if we got an auth-failed exception earlier, re-raise it
if saved_exception is not None:
raise saved_exception
raise SSHException('No authentication methods available')