python连接服务器上传文件,后台执行命令

上传文件

import os

import paramiko
import logging

from django.core.cache import cache

from YunTai import settings


def upload_files(connectIp): ssh = paramiko.Transport((connectIp, 22)) try: password = cache.get('backup_server_password') if not password: return False ssh.connect(username="root", password=password) sftp = paramiko.SFTPClient.from_transport(ssh) localfile = os.path.join(settings.BASE_DIR, 'media/authFile/dr_server') print(localfile) sftp.put(localfile, "/root/dr_server") except Exception as e: return False print("上传") ssh.close() return True

后台执行命令
def handle_server(connectIp):
cmd = '''
cd /root/dr;
mkdir old;
killall dr_server;
ls;
ls;
cd ..;
cd -;
mv -f dr_server old;
mv ../dr_server .;
chmod 777 dr_server;
./dr_start.sh;
'''

try:
server_data = cache.get('server_data')
if not server_data:
return False
connectIp = server_data.get('server_ip')
password = server_data.get('password')
cache.delete('server_data')
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(connectIp, 22, 'root', password, timeout=60)
stdin, stdout, stderr = client.exec_command('nohup /root/dr/handle_server/update_server.sh > /dev/null 2>&1 &')
client.close()
return True
except Exception as e:
print(e)
logger.error(e)
return False
posted @ 2019-03-19 15:39  我爱敲代码  阅读(1341)  评论(0编辑  收藏  举报