Zhong__AsyncSSH简单使用

时间:2021.02.24

环境:CentOS7.6.1810 两台主机 node1、node2

目的:使用python包asyncssh远程连接Linux主机

说明:

作者:Zhong QQ交流群:121160124 欢迎加入!

 

AsyncSSH is a Python package which provides an asynchronous client and server implementation of the SSHv2 protocol on top of the Python 3.6+ asyncio framework.

AsyncSSH 是一个Python包 提供了客户端和服务器的异步通讯 基于SSH v2协议 python3.6+ 框架。

简单的例子(本地连接):

import asyncio, asyncssh, sys

async def run_client():
    async with asyncssh.connect('localhost') as conn:
        result = await conn.run('echo "Hello!"', check=True)
        print(result.stdout, end='')

try:
    asyncio.get_event_loop().run_until_complete(run_client())
except (OSError, asyncssh.Error) as exc:
    sys.exit('SSH connection failed: ' + str(exc))

场景1:node1主机使用用户名、密码连接node2

在node1主机安装依赖包

pip install asyncssh

写一个脚本文件test_asyncssh.py 代码如下:

import argparse
import asyncio
import asyncssh

class AsyncExample():

    def __init__(self, username, password, host):
        self.username = username
        self.password = password
        self.host = host

    async def test(self, username, password, host):
        conn = await asyncssh.connect(host=host, username=username, password=password)

        res = await conn.run(command='hostname')
        print(res)

        conn.close()
        return

    async def gather(self):
        tasks = []
        tasks.append(self.test(self.username, self.password, self.host))
        await asyncio.gather(*tasks)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='接收参数')
    parser.add_argument('-u', '--username')
    parser.add_argument('-p', '--password')
    parser.add_argument('-ip', '--host')

    args = parser.parse_args()
    username = args.username
    password = args.password
    host = args.host

    print("username: ", username, type(username))
    print("password: ", password, type(password))
    print("目标主机: ", host, type(host))

    async def main():
        oka = AsyncExample(username, password, host)
        await oka.gather()

    asyncio.run(main())

运行脚本 传入node2主机的用户名、密码和ip

python test_asyncssh.py --username root --password yourpassword --host 192.168.1.2

场景2:node1主机使用known_hosts或者id_dsa连接node2

如果在node1使用dsa算法(其它加密算法同理)生成了密钥并把公钥导入了node2的authorized_keys 那么可以基于密钥来进行认证

test_asyncssh.py修改为如下:

import argparse
import asyncio
import asyncssh

class AsyncExample():

    def __init__(self, host, username):
        self.host = host
        self.username = username

    async def test(self, host, username):
        conn = await asyncssh.connect(host=host, username=username)
        # conn = await asyncssh.connect(host=host)  如果是root用户认证执行则不需要传递用户名

        res = await conn.run(command='hostname')
        print(res)

        conn.close()
        return

    async def gather(self):
        tasks = []
        tasks.append(self.test(self.host, self.username))
        await asyncio.gather(*tasks)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='接收参数')
    parser.add_argument('-ip', '--host')
    parser.add_argument('-u', '--username')

    args = parser.parse_args()
 
    host = args.host
    username = args.username

    print("目标主机: ", host, type(host))

    async def main():
        oka = AsyncExample(host, username)
        await oka.gather()

    asyncio.run(main())

运行脚本 传入node2主机的ip

python test_asyncssh.py --host 192.168.1.2 --username develop

默认情况下 会传入当前用户~/.ssh/目录下的known_hosts和id_dsa到asyncssh.connect()选项里即asyncssh.connect(known_hosts='~/.ssh/known_hosts', client_keys=['~/.ssh/id_dsa'])来进行认证

只要有一项通过就可以连接  所以如果想使用密钥认证的话 只要在asyncssh.connect()里指定known_hosts='known_hosts文件路径'或者client_keys=['id_dsa文件路径']或者两个都指定即可

 

关注微信公众号:

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我变了_我没变

随意 。。。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值