标签:操作 HCL local python tde def username settime ignore
paramiko基于SSH连接ssh Server执行操作(SSHClient远程连接,SFTPClient上传下载)
pip install paramiko
import paramiko
ssh = paramiko.SSHClient() # 创建ssh客户端
know_hosts = paramiko.AutoAddPolicy() # 创建ssh白名单
ssh.set_missing_host_key_policy(know_hosts) # 加载白名单
ssh.connect( # 链接server
hostname=‘192.168.100.41‘,
port=22,
username=‘root‘,
password=‘aegis‘
)
stdin, stdout, stderr = ssh.exec_command(‘ip r‘) # 执行命令
print(stdout.read().decode(encoding=‘utf8‘))
ssh.close()
from settings import pool
import paramiko, threading
class ParamikoThreading(threading.Thread):
def __init__(self, host, username, password, port=22, command=‘ip a‘):
self.host = host
self.username = username
self.password = password
self.port = port
self.command = command
super(ParamikoThreading,self).__init__()
def run(self) -> None:
ssh=paramiko.SSHClient()
know_hosts=paramiko.AutoAddPolicy()
ssh.set_missing_host_key_policy(know_hosts)
ssh.connect(
hostname=self.host,
port=self.port,
username=self.username,
password=self.password
)
stdin,stdout,stderr=ssh.exec_command(self.command)
print(‘*‘*60)
print(‘ip:%s,\ncommand:%s,\n‘ % (self.host,self.command))
print(stdout.read().decode(encoding=‘utf8‘))
print(‘*‘*60)
ssh.close()
if __name__ == ‘__main__‘:
command=‘ip a‘
t_pool=[]
for host in pool:
t=ParamikoThreading(
host=host.get(‘host‘,‘localhost‘),
username=host.get(‘username‘,‘root‘),
password=host.get(‘password‘,‘aegis‘),
command=command
)
t_pool.append(t)
for t in t_pool:
t.start()
for t in t_pool:
t.join()
settings.py
pool=[
dict(host=‘192.168.100.41‘,username=‘root‘,password=‘aegis‘),
dict(host=‘192.168.100.42‘,username=‘root‘,password=‘aegis‘),
dict(host=‘192.168.100.43‘,username=‘root‘,password=‘aegis‘),
]
import paramiko
ssh=paramiko.SSHClient()
know_hosts=paramiko.AutoAddPolicy()
ssh.set_missing_host_key_policy(know_hosts)
ssh.connect(
hostname=‘192.168.100.41‘,
username=‘root‘,
password=‘aegis‘,
port=22
)
shell=ssh.invoke_shell()
shell.settimeout(1)
command=input(‘>>>‘+‘\n‘)
shell.send(bytes(command,encoding=‘utf8‘))
while True:
try:
recv=shell.recv(1024).decode(encoding=‘utf8‘,errors=‘ignore‘)
if recv:
print(recv)
else:
continue
except:
command=input(‘>>>‘+‘\n‘)
shell.send(bytes(command,encoding=‘utf8‘))
ssh.close()
import paramiko
trans=paramiko.Transport(
sock=(‘192.168.100.41‘,22)
)
trans.connect(
username=‘root‘,
password=‘aegis‘
)
sftp=paramiko.SFTPClient.from_transport(trans)
# upload
# sftp.put(‘settings.py‘,‘/root/settings.py‘)
# download
sftp.get(‘/root/oom.c‘,‘oom.c‘)
sftp.close()
标签:操作 HCL local python tde def username settime ignore
原文地址:https://www.cnblogs.com/dissipate/p/14668191.html