import paramiko
import os
from paramiko import AuthenticationException
from paramiko.ssh_exception import NoValidConnectionsError
class ParamikoHelper():
def __init__(self,
remote_ip,
remote_ssh_port="22",
ssh_password=None,
ssh_username="root",
private_key_path=None):
self.ssh = paramiko.SSHClient()
self.remote_ip = remote_ip
self.remote_ssh_port = remote_ssh_port
self.ssh_password = ssh_password
self.ssh_username = ssh_username
self.private_key_path = private_key_path
def __enter__(self):
try:
# 设置允许连接known_hosts文件中的主机(默认连接不在known_hosts文件中的主机会拒绝连接抛出SSHException)
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
# 连接服务器
self.ssh.connect(hostname=self.remote_ip,
port=self.remote_ssh_port,
username=self.ssh_username,
password=self.ssh_password,
key_filename=self.private_key_path,
timeout=60)
except AuthenticationException as e:
# logging.warning('username or password error')
print('username or password error')
raise e
# return 1001
except NoValidConnectionsError as e:
# logging.warning('connect time out')
print('connect time out')
raise e
# return 1002
except Exception as a:
print('Unexpected error:', sys.exc_info()[0])
raise a
# return 1003
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# 关闭服务器连接
self.ssh.close()
def exec_shell(self, shell):
stdin, stdout, stderr = self.ssh.exec_command(shell)
return stdout.read().decode(), stderr.read().decode()
def sftp_put_file(self, local_file, remote_file):
with self.ssh.open_sftp() as sftp:
try:
sftp.put(local_file, remote_file)
except FileNotFoundError as e:
print("No such file!")
raise e
def sftp_get_file(self, local_file, remote_file):
with self.ssh.open_sftp() as sftp:
try:
sftp.get(local_file, remote_file)
except FileNotFoundError as e:
print("No such file!")
raise e
def main():
ph_config = {
"remote_ip": "192.168.153.32",
"remote_ssh_port": 22,
"ssh_username": "root1",
# "private_key_path": "/root/.ssh/yunwei"
"ssh_password": "root"
}
try:
with ParamikoHelper(**ph_config) as ph:
# ph = ParamikoHelper(**ph_config)
# 远程执行ssh命令
shell = "hostname"
ret = ph.exec_shell(shell)
print(ret)
ret = ph.sftp_put_file("./db.py", "/root/123/db.py")
print(ret)
except Exception as e:
pass
if __name__ == '__main__':
main()