zoukankan      html  css  js  c++  java
  • Python远程控制连接Linux操作(替代Jenkins)

     1 import paramiko
     2 import getpass
     3 
     4 # 远程设备的IP 端口 用户名 密码
     5 IP = "10.8.12.45"
     6 port = 22
     7 remote_username = "uos-0804"
     8 remoet_password = "1"
     9 # 包名
    10 package_name = "0811.zip"
    11 # 本机用户名
    12 my_username = getpass.getuser()
    13 
    14 # 建立连接
    15 transport = paramiko.Transport((IP, port))
    16 transport.connect(username=remote_username, password=remoet_password)
    17 
    18 # 创建SSH对象
    19 ssh = paramiko.SSHClient()
    20 ssh._transport = transport
    21 
    22 
    23 # 执行命令
    24 def cmd(doit):
    25     # ssh.exec_command(doit)
    26     stdin, stdout, stderr = ssh.exec_command(doit)
    27     back_word = stdout.read().decode()
    28     return back_word
    29 
    30 
    31 # 上传文件
    32 def put_file():
    33     sftp = paramiko.SFTPClient.from_transport(transport)
    34     # from my_path to remote_path
    35     my_path = "/home/%s/Documents/%s" % (my_username, package_name)
    36     remote_path = "/home/%s/Documents/%s" % (remote_username, package_name)
    37     sftp.put(my_path, remote_path)
    38 
    39 
    40 # 解压
    41 def unzip():
    42     cmd("cd /home/%s/Documents/ && unzip %s" % (remote_username, package_name))
    43 
    44 
    45 # 执行测试
    46 def exec_test():
    47     cmd("cd /home/%s/Documents/media_automation_test/report/ && bash start_runner.sh" % remote_username)
    48 
    49 
    50 # 关闭连接
    51 def close():
    52     ssh.close()
    53 
    54 
    55 
    56 def delete_package():
    57     doit = "cd /home/%s/Documents/ && rm -rf %s" % (remote_username, package_name)
    58     stdin, stdout, stderr = ssh.exec_command(doit)
    59     #stdin.write(remoet_password + r'
    ')
    60     #stdin.flush()
    61 
    62 def delete_folder():
    63     doit = "cd /home/%s/Documents/ && rm -rf media_automation_test" % remote_username
    64     stdin, stdout, stderr = ssh.exec_command(doit, get_pty=True)
    65     #stdin.write(remoet_password + r'
    ')
    66     #stdin.flush()
    67 
    68 
    69 # 上传项目包
    70 put_file()
    71 # 解压
    72 unzip()
    73 # 执行测试
    74 exec_test()
    75 # 删除项目包
    76 delete_package()
    77 # 删除项目文件夹
    78 delete_folder()
    79 
    80 
    81 close()

    遇到的问题:

    在远程批量执行测试用例的时候,测试用例执行失败,报错:KeyError:"DISPLAY"

    解决1:在python脚本里面添加  

    import os 
    os.environ[ "DISPLAY" ] = ":0"

     解决2:在shell脚本里面添加

    export DISPLAY=:0
    没伞的孩子,就要学会在雨中奔跑!
  • 相关阅读:
    菜单无限极分类核心代码
    获取页面中更新删除传过来的id
    CI循环数组问题
    ci框架model中的进行增删改的写法
    MySQL DBA的修炼与未来(参考篇)
    Linux学习笔记(13)linux软件安装rpm与yum--理论篇
    Linux学习笔记(12)linux文件目录与用户管理
    Linux学习笔记(11)linux网络管理与配置之一——配置路由与默认网关,双网卡绑定(5-6)
    Linux学习笔记(10)linux网络管理与配置之一——主机名与IP地址,DNS解析与本地hosts解析(1-4)
    自定义流水号,前置加0
  • 原文地址:https://www.cnblogs.com/mikigo/p/13489090.html
Copyright © 2011-2022 走看看