基于paramiko单用户名方式建立ssh连接

基于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')
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值