Python sshpass本地传文件到远端及服务重启

 脚本使用模块: sshpass

特点:1. 自动指纹校验;2.指定密码和目录传输文件。

 

# -*- coding: utf8 -*-
# /usr/bin/python

import subprocess, sys
import os, commands
afb = "/opt/xdfs-mgnt/mgnt-agent/agent/"
alfb = "xdfs-restful/xdfs-mgnt-agent/src/agent/"
agent_file = ["hardwares/scsi.py", "xfile.py", "hardwares/nvmeof.py", "hardwares/cmd_outputs",
            "solve_nfs_cifs_ftp.py", "glusterfs_shares.py", "sharing_openrations.py", "hardware.py", "xfile_quota.py", "xdfs_s3", "celery.py",
            "glusterfs_volumes.py"
        ]
mfb = "/opt/xdfs-mgnt/mgnt-master/"
mlfb = "xdfs-restful/xdfs-mgnt-master/src/"
master_file = ["agent", "xfiles","nodes", "clusters", "devices", "monitors", "bricks", "volumes", "disks", "hosts", "shares", "server", "disks", "objstorageminio"
        ]



def scp_method(ip, agent=''):
    # 当ssh 使用-o stricthostkeychecking=no后,会注册进host_knowns文件,所以scp 不需要写-o stricthostkeychecking=no了, 即使写也会报错。
    cmd = "sshpass -p 111111 ssh -o stricthostkeychecking=no root@%s ls" % ip
    ret = commands.getstatusoutput(cmd)
    print ret
    local_files = os.listdir('.')
    if alfb.split('/')[0] not in local_files:
        return
    if agent == 'agent':
        for el in agent_file:
            #cmd = "sshpass -p 111111 ssh -P 22 root@%s: rm -rf %s" % (ip, el)
            #os.system(cmd)
            print el
            if 'hardwares' in el:
                cmd = "sshpass -p 111111 scp -P 22 -r %s root@%s:%s" % (alfb + el, ip, afb + "hardwares")
            else:
                cmd = "sshpass -p 111111 scp -P 22 -r %s root@%s:%s" % (alfb + el, ip, afb)
            os.system(cmd)
        cmd = "sshpass -p 111111 ssh root@%s systemctl restart xdfs-mgnt-agent" % ip
        os.system(cmd)
    else:
        for el in master_file:
            # 因为xfiles 中的migrations文件,所以不能移除。
            #cmd = "sshpass -p sysadmin ssh -P 2222 root@%s: rm -rf %s" % (ip, el)
            #os.system(cmd)
            print el
            cmd = "sshpass -p sysadmin scp -P 2222 -r %s root@%s:%s" % (mlfb + el, ip, mfb )
            os.system(cmd)
        # 不生效
        #cmd = "sshpass -p sysadmin ssh -P 2222 root@%s systemctl restart httpd" % ip
        #os.system(cmd)
            
def main():
    if len(sys.argv) < 3:
        print "need input params"
    scp_method(sys.argv[1], sys.argv[2])
    print 'transaction success.'

if __name__ == "__main__":
    # python scp_file.py ip agent/master
    main()

 

你可能感兴趣的:(python脚本)