예제 #1
0
def exec_ssh_command(ssh,command):
    try:
        stdin,stdout,stderr = ssh.exec_command(command)
        channel = stdout.channel
        status = channel.recv_exit_status()
        print("status",status)
        if status==0:
            print("已经连接到该主机%s:%s,mkdir -p命令执行成功" %(ip,port))
        else:
            print("执行命令%s报错,请查看日志"% (status))
            log.error(str(stderr.read()))
            print (stderr.read().decode('utf-8'))
    except Exception as e:
        print (stderr.read().decode('utf-8'),log.error(str(e)))
예제 #2
0
def add_config(filename,
               sections='default',
               ip='127.0.0.1',
               port=22,
               user='******',
               passwd='root',
               **key):
    '''
                    生成配置文件, 字典的形式添加数据
    '''
    try:
        config = ConfigObj(filename, encoding='utf-8')
        #config.initial_comment(sections)
        config[sections] = {}
        config[sections]['ip'] = ip
        config[sections]['port'] = port
        config[sections]['user'] = user
        config[sections]['passwd'] = passwd
        #添加多余的配置字段
        for k, v in key.items():
            config[sections][k] = v
        print(sections, config[sections])
        config.write()
    except Exception as e:
        print("config初始化异常", str(e), log.error(str(e)))
예제 #3
0
def download_dir(ip, port, username, password, local_dir, remote_dir):
    """下载远程服务器的目录中所有文件 ,目录到本地的local_dir目录之下,该local_dir下面包括远程服务器remote_dir的所有目录
    """
    print("log_file", log_file)
    print("开始下载")
    try:
        #paramiko.util.log_to_file("/logs/paramiko.log")
        trans = paramiko.Transport((ip, int(port)))
        trans.connect(username=username, password=password)
        sftp = paramiko.SFTPClient.from_transport(trans)
        try:
            print(get_all_files_in_remote_dir(sftp, remote_dir))
            list_files = get_all_files_in_remote_dir(sftp, remote_dir)
            print("list_files", list_files)
            for file in list_files:
                #print("DIR",)
                #print("local_dir",local_dir)
                dir = os.path.dirname(file)
                #print("tempdir",dir)
                #如果本地路径最后一个不是/刚加上/
                if local_dir[-1] == '/':
                    local_dir = local_dir[:-1]
                #print("local_dir",local_dir)
                full_path = local_dir + dir + '/'
                #本地对应的文件
                full_file = local_dir + file
                #print("full_file",full_file)
                #远程机器上的文件
                #print("file",file)
                if not os.path.isdir(full_path):
                    try:
                        os.makedirs(full_path)
                        #print("assss",os.path.split(path)[0])
                        print("目录创建成功", full_path)
                    except Exception as err:
                        print("创建目录时报错", str(err), log.error(str(err)))
                else:
                    print("已创建")
                sftp.get(file, full_file)
        except Exception as e:
            print("files err", log.error(str(e)))
#             for f in files:
#                 print ('Downloading file:',os.path.join(remote_dir,f))
#sftp.get(os.path.join(remote_dir,f),os.path.join(local_dir,f))
    except Exception as e:
        print(log.error(str(e)))
        trans.close()
예제 #4
0
def update_config(filename, sections, options, value):
    try:
        config = ConfigObj(filename, encoding='UTF8')
        config[sections][options] = value
        #修改一个sections
        #config.rename(sections, 'sss')
        config.write()
    except Exception as e:
        print("config初始化异常", str(e), log.error(str(e)))
예제 #5
0
def config_write(sections='default',
                 ip='127.0.0.1',
                 port=22,
                 user='******',
                 passwd='root',
                 **key):
    '''
                    生成配置文件, 字典的形式添加数据
    '''
    print("函数参数个数", inspect.getargspec(config_write))
    try:
        config = configparser.ConfigParser()
        config[sections] = {
            'ip': ip,
            'port': port,
            'user': user,
            'passwd': passwd,
        }
        #for k,v in key.items():
        #config[sections][k]=v
        #print("value",v)


#         config['web']={}
#         config['web']['ip']='192.168.0.1'
#         config["mysql"]={}
#         topsecret=config['myssql']#这种操作还是在操作mysql这个sections
#         topsecret['ip']='127.0.0.1'
#         topsecret['user']='******'
    except Exception as e:
        print("config初始化异常", str(e), log.error(str(e)))
    try:
        with open('config.ini', 'w') as configfile:
            print("添加sections", sections)
            config.add_section(sections)
            config.set(sections, "ip", ip)
            config.set(sections, "port", str(port))
            config.set(sections, "user", user)
            config.set(sections, "passwd", passwd)
            print("写入配置文件")
            config.add_section('ass')
            config.write(configfile)
    except Exception as e:
        print("打开文件异常", str(e), log.error(str(e)))
예제 #6
0
def read_sections(filename, sections):

    dict_value = {}
    try:
        config = ConfigObj(filename, encoding='UTF8')
        for k, v in config[sections].items():
            dict_value[k] = v
        return dict_value
    except Exception as e:
        print("config err", log.error(str(e)))
예제 #7
0
def del_config(filename, sections, options):
    try:
        config = ConfigObj(filename, encoding='UTF8')
        if validate_config(filename, sections, options):
            del config[sections][options]
            config.write()
        else:
            print("ther is no that options")
    except Exception as e:
        print("config err", log.error(str(e)))
예제 #8
0
def return_paramiko_connect(ip,port,username,password,logfile=logfile):
    #创建paramiko连接,用于传输文件
    try:
        paramiko.util.log_to_file("../logs/paramiko.log")  
        trans = paramiko.Transport((ip, int(port)))  
        trans.connect(username=username, password=password)  
        sftp = paramiko.SFTPClient.from_transport(trans)  
    except Exception as e:
        print ("连接%s:%s时报错,请查看日志%s" % (ip,port,logfile),str(e),'\n',log.error(str(e)))
        #记录IP加端口,将其写入未连接成功的配置文件中
    return sftp
예제 #9
0
def python_ssh_command(ip,
                       port,
                       username,
                       password,
                       logfile='../logs/command.log',
                       **shell):
    from loggingclass import log
    log = log(logfile)
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(
            paramiko.AutoAddPolicy())  # 用于允许连接不在known_hosts名单中的主机
        ssh.connect(ip, port, username, password)
        result = {}
        for key in shell:
            try:
                stdin, stdout, stderr = ssh.exec_command(shell[key])
                channel = stdout.channel
                status = channel.recv_exit_status()
                print("status", status)
                if status == 0:
                    print("已经连接到该主机%s:%s,%s:命令执行成功" % (ip, port, shell[key]))
                    #打印命令输出结果
                    #print (stdout.read().decode('utf-8'))
                else:
                    print("执行命令%s报错,请查看日志" % (shell[key]))
                    log.error(str(stderr.read()))
                    print(stderr.read().decode('utf-8'))
            except Exception as e:
                print(stderr.read().decode('utf-8'), log.error(str(e)))
            #stdin,stdout,stderr = ssh.exec_command(shell[key])
            #print("key",key)
            result[key] = stdout.read().decode('utf-8'), stderr.read().decode(
                'utf-8')
        ssh.close()
        print("result", result, type(result))
        return result
    except Exception as e:
        result = u'无'
        print("异常", str(e))
        return result
예제 #10
0
def mkdir_path(dir):
    #判断是否是个目录
    if os.path.isdir(dir):
        #判断目录是否存在
        if not os.path.exists(dir):
            try:
                os.mkdir(dir)
            except Exception as e:
                print(log.error(str(e)))
        else:
            print("%s已存在该目录" % dir)
    else:
        print("s%这不是一个目录" % dir)
예제 #11
0
def return_ssh_connect(ip,port,username,password,logfile=logfile):
    #创建SSH连接用于执行命令
    try:
        ssh = paramiko.SSHClient()
        paramiko.util.log_to_file('../logs/ssh.log')
        #允许连接不在know_hosts文件中的主机
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        print("ip+端口",ip,port)
        ssh.connect(ip, int(port),username, password,timeout=1)
    except Exception as e:
        print ("连接%s:%s时报错,请查看日志%s" % (ip,port,logfile),str(e),'\n',log.error(str(e)))
        #记录IP加端口,将其写入未连接成功的配置文件中
        #将连接异常的IP写入到数据库,这里是写入到一个配置文件中
    return ssh
예제 #12
0
def ssh_connect_command(logfile,ip,port,username,password,command):
    no_con_server=[]
    try:
        ssh = paramiko.SSHClient()
        paramiko.util.log_to_file('../logs/ssh.log')
        #允许连接不在know_hosts文件中的主机
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        print("ip+端口",ip,port)
        ssh.connect(ip, int(port),username, password,timeout=1)
        try:
            stdin,stdout,stderr = ssh.exec_command(command)
            channel = stdout.channel
            status = channel.recv_exit_status()
            print("status",status)
            if status==0:
                print("已经连接到该主机%s:%s,%s命令执行成功" %(ip,port,command))
                #打印执行的命令
                print (stdout.read().decode('utf-8'))
            else:
                print("执行命令%s报错,请查看日志"% (status,logfile))
                log.error(str(stderr.read()))
                print (stderr.read().decode('utf-8'))
                sessions=ip+":"+port
                #执行命令异常的IP写入到数据库,这里是写入到一个配置文件中
                add_config(conf_ini,sessions,ip,port,username,password)
        except Exception as e:
            print ("执行命令%s时报错,请看日志" % command,logfile,'\n',stderr.read().decode('utf-8'),log(str(e)))
            sessions=ip+":"+port
            #执行命令异常的IP写入到数据库,这里是写入到一个配置文件中
            add_config(conf_ini,sessions,ip,port,username,password)
    except Exception as e:
        print ("连接%s:%s时报错,请查看日志%s" % (ip,port,logfile),str(e),'\n',log.error(str(e)))
        #记录IP加端口,将其写入未连接成功的配置文件中
        sessions=ip+":"+port
        #将连接异常的IP写入到数据库,这里是写入到一个配置文件中
        add_config(conf_ini,sessions,ip,port,username,password)
예제 #13
0
def validate_config(filename, sections, options):
    try:
        config = ConfigObj(filename, encoding='UTF8')
        #判断是否存在sections
        value1 = config.get(sections)
        if value1:
            #判断是否存在options
            value2 = config.get(sections).get(options)
            if value2:
                return True
            else:
                return False
        else:
            return False
    except Exception as e:
        print("config err", log.error(str(e)))
예제 #14
0
def read_theSames(filename, same):
    '''
    same是同一组机器的共性命名,
    [web1][web2][web4]----same=web
     read_theSames(filename,web)
    '''
    dict_value = {}
    count = len(same)
    print("same位数", count)
    try:
        config = ConfigObj(filename, encoding='UTF8')
        #items = config.popitem()
        items = config.iteritems()
        for k, v in items:
            if k[0:count] == same:
                dict_value[k] = v
        return dict_value
    except Exception as e:
        print("config err", log.error(str(e)))
예제 #15
0
def read_config_file(logfile):
    '''''Read_config_file(filename) 
 
        this function is used for parse the config file'''
    #定义一个方法
    cofile = './property.config'
    data = {}
    config = configparser.ConfigParser()
    try:
        with open(cofile, 'r') as confile:
            config.readfp(confile)
            #config.read(filename)
            for i in config.sections():
                for (key, value) in config.items(i):
                    data[key] = value
                print(log.info(str(value)))
            return data
    except Exception as e:
        print("Open file error.", log.error(str(e)))
예제 #16
0
def read_all(filename):
    '''
            常见方法
    ‘items’
    ‘iteritems’
    ‘iterkeys’
    ‘itervalues’
    ‘keys’
    ‘popitem’
    ‘values’
    '''
    dict_value = {}
    try:
        config = ConfigObj(filename, encoding='UTF8')
        #items = config.popitem()
        items = config.iteritems()
        for k, v in items:
            dict_value[k] = v
        return dict_value
    except Exception as e:
        print("config err", log.error(str(e)))