Created
April 18, 2024 12:43
-
-
Save kona3266/102bd3e893ba26445787778b03d5f358 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import paramiko | |
import asyncio | |
import time | |
import asyncssh | |
import sys | |
pubkey_str = '' | |
with open("/root/.ssh/id_rsa.pub") as f: | |
pubkey_str += f.read() | |
pubkey_str = pubkey_str.replace("\n", "") | |
def ssh_copy(host): | |
try: | |
clt = paramiko.client.SSHClient() | |
clt.load_system_host_keys() | |
clt.set_missing_host_key_policy(paramiko.client.AutoAddPolicy) | |
print("connect with passwd") | |
clt.connect(host, username="root", password=passwd) | |
cmd = "echo %s >> /root/.ssh/authorized_keys" % pubkey_str | |
stdin, stdout, stderr = clt.exec_command(cmd) | |
output = stdout.read().decode("utf-8") | |
print("output :", output) | |
finally: | |
if clt: | |
clt.close() | |
async def run_client(host): | |
async with asyncssh.connect(host, username="root", password=passwd, known_hosts=None) as conn: | |
cmd = "echo %s >> /root/.ssh/authorized_keys" % pubkey_str | |
result = await conn.run(cmd, check=True) | |
async def ssh_async(): | |
await asyncio.gather(*[run_client(host) for host in hosts]) | |
def usage(): | |
print("usage: -h $host_ip1,$host_ip2 -p $passwd") | |
sys.exit(1) | |
def parse_arg(args): | |
hosts = None | |
passwd = None | |
for i,v in enumerate(args): | |
if v == "-h": | |
hosts = args[i+1].split(",") | |
elif v == "-p": | |
passwd = args[i+1] | |
if not hosts or not passwd: | |
usage() | |
return hosts, passwd | |
if __name__ == "__main__": | |
args = sys.argv[1:] | |
hosts, passwd = parse_arg(args) | |
start = time.time() | |
for i in hosts: | |
ssh_copy(i) | |
print("TIME", time.time()-start) | |
start = time.time() | |
asyncio.run(ssh_async()) | |
print("TIME", time.time()-start) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment