服务器中利用Python调用Linux命令传输文件到本机

首先在服务器中安装 rz/sz 命令:

yum -y install lrzsz

python程序:

config.py

为了方便之后参数的整体调整,指定可以先制定python操作后可能要用到的参数

# -*- coding: utf-8 -*-
import argparse


class ConfigParser:
    def __init__(
            self,
            host='',
            username='',
            port='',
            sever_file='',
            local_file=''
    ):
        '''
        Server parameters
        :param host: server address
        :param username:user name
        :param port:port
        :param sever_file:Server file path
        :param local_file:Local file path
        '''


        self.parser = argparse.ArgumentParser(description='Configuration file')
        self.arg_lists = []
        # Data
        data_arg = self.add_argument_group('Data')
        data_arg.add_argument('--host', type=str, default=host, help='sever host')
        data_arg.add_argument('--username', type=str, default=username, help='sever name')
        data_arg.add_argument('--port', type=str, default=port, help='server port')
        data_arg.add_argument('--sever_file', type=str, default=sever_file, help='sever file path')
        data_arg.add_argument('--local_file', type=str, default=local_file, help='local file path')

    def add_argument_group(self, name):
        arg = self.parser.add_argument_group(name)
        self.arg_lists.append(arg)
        return arg

    def get_config(self):
        self.config, self.unparsed = self.parser.parse_known_args()
        return self.config

    def print_config(self):
        print('\n')
        print('Data Config:')
        print('* city num:', self.config.city_num)
        print('* individual num:', self.config.individual_num)
        print('* generation num:', self.config.gen_num)
        print('* probability of mutate:', self.config.mutate_prob)


if __name__ == '__main__':
    Cf = ConfigParser()
    config = Cf.get_config()
    print("local file path:", config.local_file)
    print("sever file path:", config.sever_file)

transfer_file.py

import os
import sys
sys.path.append('……')
from config import ConfigParser
'''
    此脚本用于python调用Linux命令,使得Linux服务器与本地能够双向传输文件
'''

Cf = ConfigParser(sever_file='……')
config = Cf.get_config()
print('server address', config.host)
print('user name', config.username)
print('port', config.port)
print('Server file path', config.sever_file)
print('Local file path', config.local_file)



def To_local(
        host='……',
        username='……',
        port='……',
        sever_file='……',
        local_file='……'
):
    if os.path.isdir(sever_file):
        print('It is a dictionary.')
    else:
        print('It is not a dictionary.')

    os.system(f'sz {sever_file}')

To_local(sever_file='……')

你可能感兴趣的:(Python,服务器,centos,运维)