python 通过paramiko自动上传到linux服务器并运行
import paramiko, time, sys, traceback, os
class SSHUtils:
def __init__(self, ip, username, passwd, port=22):
self.ip = ip
self.port = port
self.username = username
self.passwd = passwd
def upload(self, file_path, origin_file_path):
trans = paramiko.Transport((self.ip, self.port))
trans.connect(username=self.username, password=self.passwd)
sftp = paramiko.SFTPClient.from_transport(trans)
try:
sftp.put(file_path, origin_file_path)
trans.close()
print('上传成功')
except Exception as e:
print(e)
def exec_ssh_command(self, ssh_command):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=self.ip, port=self.port, username=self.username, password=self.passwd, timeout=10)
client = ssh.invoke_shell()
client.send(ssh_command + '\n')
res = ''
while not res.endswith('# '):
time.sleep(1)
res += client.recv(65535).decode('utf-8')
ssh.close()
return res
except:
type, value, tb = sys.exc_info()
return traceback.format_exception(type, value, tb)
def exec_command(self, ssh_command):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=self.ip, port=self.port, username=self.username, password=self.passwd, timeout=10)
stdin, stdout, stderr = ssh.exec_command(ssh_command)
result = stdout.read().decode('utf-8')
ssh.close()
return result
if __name__ == '__main__':
f_path = r"c:/xxxx/admin.jar"
o_file_path = r"/opt/service/admin.jar"
stop_cmd = "cd /opt/service/ && sh admin.sh stop && rm -rf admin.jar"
start_cmd = "cd /opt/service/ && sh admin.sh start"
ipaddr = "xxx.xx.xx.xxx"
user_name = "xxx"
password = "xxx"
if os.access(f_path, os.X_OK):
myssh = SSHUtils(ipaddr, user_name, password)
ret = myssh.exec_command(stop_cmd)
print(ret)
myssh.upload(f_path, o_file_path)
ret = myssh.exec_ssh_command(start_cmd)
print(ret)
else:
print("jar包不存在,请先打jar包后再执行...")