python scp指令自动填充用户名和密码
本地想要传输文件到 ARM
板卡中,可以使用 scp
命令,但是需要手动填写scp指令,例如:1
scp filepath root@192.168.137.89:/home/root/
执行时还需要手动输入IP、路径、密码等,所以写了一个脚本可以自动完成指令和密码的填充。同时处理了第一次传输文件时的密钥处理,可以在系统提示时自动填入 Y
进行确认。
其中使用了 pexpect
库,可以通过 pip install pexpect
指令安装。
代码如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48#!/usr/bin/env python3
import sys
import pexpect
import os
'''本脚本用于实现scp指令将上位机文件传输给板卡 并自动填充目标ip地址和用户名密码'''
class LogWrapper:
def __init__(self, file):
self.file = file
def write(self, data):
self.file.write(data.decode('utf-8'))
self.file.flush()
def flush(self):
self.file.flush()
if __name__ == '__main__':
filepath = sys.argv[1]
if len(sys.argv) > 2:
dst_path = ' root@192.168.137.89:/home/root/' + sys.argv[2]
else:
dst_path = ' root@192.168.137.89:/home/root/'
command = "scp " + filepath + ' ' + dst_path
password = "root"
print(command)
# Remove old host key if it exists
known_hosts_file = "~/.ssh/known_hosts"
ip_address = "192.168.137.89"
remove_command = f"ssh-keygen -f \"{known_hosts_file}\" -R \"{ip_address}\""
os.system(remove_command)
# Execute SCP command
child = pexpect.spawn(command, logfile=LogWrapper(sys.stdout))
index = child.expect(["Are you sure you want to continue connecting (yes/no)?", "password:", pexpect.EOF])
if index == 0:
child.sendline("yes")
child.expect("password:")
if index in [0, 1]:
child.sendline(password)
child.expect(pexpect.EOF)
print(child.before.decode())
执行时通过以下命令即可:1
./scp.py filename