时间: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文件路径']或者两个都指定即可
关注微信公众号: