示例
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 自动添加主机名及主机密钥到本地 HostKeys 对象,默认是拒绝未知的 ssh 服务器连接
ssh.connect('node', username='your_username', password='your_password') # 连接到远程服务器
# 执行你的命令
stdin, stdout, stderr = ssh.exec_command('cd /home/mazu/run_path; nohup ./nio_4d_dynamic_pub_app > /dev/null 2>&1 &')
# 关闭连接
ssh.close()
已知问题,paramiko执行不会执行环境变量,并且尚未解决的是,执行环境变量,再执行paramiko的命令还是会报错,变更方法
示例
import subprocess
command = 'ssh node "cd /home/mazu/run_path; nohup ./pub_app &" > /dev/null'
process = subprocess.Popen(command, shell=True)
示例二
import paramiko, time, os
class Remote:
# 初始化ip地址和端口,远程链接
def __init__(self):
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(hostname='ip', port=22, username='hostname', password='passwd', timeout=10)
def cmd(self):
try:
stdin, stdout, stderr = self.ssh.exec_command('ls')
print(stdout, stderr)
except:
if self.reconnected():
stdin, stdout, stderr = self.ssh.exec_command('ls')
else:
os.exit(-1)
def is_connected(self):
transport = self.ssh.get_transport()
if transport is not None and transport.is_active():
return True
return False
def reconnected(self):
for i in range(0, 180):
if not self.is_connected():
try:
self.ssh.connect(hostname='ip', port=22, username='hostname', password='passwd', timeout=10)
return True
except:
print('尝试一次失败链接')
time.sleep(1)
return False
remote = Remote()
while True:
remote.cmd()