Python操作服务器


# Python 控制服务器
#
# system执行命令

import os

os.system('dir')

# subprocess 执行命令

import subprocess

subprocess.run('ls')  # 执行命令
subprocess.run(['df', '-h'])  # 执行带参数的命令

subprocess.Popen('ls')  # 在新进程执行子程序 ,返回一个对象
subprocess.Popen('df -h'.split(' '))  # 执行带参数的命令

# subprocess run 取结果

cp = subprocess.run('ls', stdout=subprocess.PIPE, encoding='utf-8')
cp.stdout.splitlines()

# 以shell方式执行命令,并检查,如果错误,抛出异常

cp = subprocess.run('ls', stdout=subprocess.PIPE, encoding='utf-8', shell=True, check=True)


# Popen 执行命令

def get_list():
    proc = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)
    data = proc.stdout.read().decode()
    return data


# communicate 接受Popen结果 推荐

def get_list():
    proc = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)
    data, err = proc.communicate()
    return data.decode()


# Paramiko 的使用
# 建立 SSH连接

import paramiko

IP = '192.168.66.189'
USER = 'root'
PWD = 'dongli.1992'

paramiko.util.log_to_file('dongli.log')  # 启动日志


def connect(host, user, pwd):
    """建立连接"""
    client = None
    try:
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(host, username=user, password=pwd)
        return client
    except Exception as e:
        print(e)
        return client


def send_cmd(client, cmd):
    """发送命令"""
    try:
        stdin, stdout, stderr = client.exec_command(cmd)
        return stdout, stderr
    except paramiko.SSHException as e:
        print(e)


def put_file(client, source, remote, active):
    """上传下载文件"""
    if client:
        try:
            ftp_client = client.open_sftp()
            if active == 'put':
                ftp_client.put(source, remote)
                ftp_client.close()
                print('上传成功!')
            elif active == 'down':
                ftp_client.get(remote, source)
                ftp_client.close()
                print('下载成功!')
        except Exception as e:
            print(e)


if __name__ == '__main__':

    print('paramiko is ok ')
    client = connect(IP, USER, PWD)
    if client:
        while True:
            cmd = input('cmd 执行命令:file 操作文件:')
            if cmd == '':
                break
            elif cmd == 'cmd':
                shell = input('>>')
                stdout, stderr = send_cmd(client, shell)
                print(stdout.read().decode(), stderr.read().decode())
            elif cmd == 'file':
                source = input('输入本地文件路径:')
                remote = input('输入远程文件路径:')
                active = input('上传 put , 下载 down:')
                put_file(client, source, remote, active)
    client.close()

# Python 命令行参数解析器

import argparse

parser = argparse.ArgumentParser('blues command line demo ...')  # 提示

# 分组
# verbose 详细信息 store_true 存储真假
group1 = parser.add_argument_group('group1', '第一组组命令')
group1.add_argument('-V', '--verbose', dest='verbose', action='store_true', help='verbose info')

# 添加参数 store 存储信息
group2 = parser.add_argument_group('group2', '第二组组命令')
group2.add_argument('-U', '--upload', dest='upload', action='store', help='upload info')

# append 追加存储多个
parser.add_argument('-D', '--down', dest='down', action='append', help='down info')

# nagrs=‘*’存储列表
parser.add_argument('-F', '--file', dest='file', action='store_true', help='file info')
parser.add_argument(dest='names', nargs='*', help='names info')

# metavar
parser.add_argument('-I', '--info', dest='info', metavar='info', help='info info')

parser.print_help()  # 打印帮助
args = parser.parse_args()  # 存储命名空间
print(args)

if args.file:
    print('OK')



最后更新于:2018-09-03 11:26:24