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'\n')
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'\n')
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

 

posted @ 2020-08-12 10:19  mikigo  阅读(385)  评论(0编辑  收藏  举报