Windows Prompt命令行和Linux的Shell脚本自动化

207 阅读1分钟

在Linux操作系统上面,使用expect工具捕获期待的字符串,使用send将自己准备好的数据重定向到标准输入流 提示找不到命令的要使用install工具安装一下

#!/usr/bin/expect -f

# 设置超时时间
set timeout 10

# 运行希望自动化的脚本并等待特定提示
spawn ./install.sh
expect {
"Please input IP of the database(请输入数据库IP):" { send "IP\r"; exp_continue}
"Please input port of the database(请输入数据库端口):" { send "5432\r"; exp_continue }
"Please input username of the database(请输入数据库用户名):" { send "postgres\r"; exp_continue}
"Please input the password of the database(请输入数据库密码):" { send "password\r"; exp_continue}
"Please input the project name(请输入项目名称):" { send "test\r"; exp_continue}
}
expect "密码:"
send "root password\r"
expect "Chinese"
send "0\r"
#继续留在命令行执行过程
interact

Windows: 使用subprocess调用命令行程序,使用标准输入向命令行缓冲区输入准备好的数据

import time
import subprocess
#想要自动化的程序
command = "D:\WorkSpace\ProjectCreator\\x86_64_Windows\\bin\\ProjectCreator.exe"
#准备好将要输入的数据
IP = "IP\n"
port= "5432\n"
user= "postgres\n"
password= "password\n"
proname= "testful\n"

def auto_input_command_line():

    # 启动命令行程序,并设置 stdin=PIPE 以便后续自动填充输入
    process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8')
    # 向标准输入文件对象写入数据
    process.stdin.write(IP)
    #刷新缓冲区
    process.stdin.flush()
    time.sleep(2)
	
	#重复操作
    process.stdin.write(port)
    process.stdin.flush()
    time.sleep(2)

    process.stdin.write(user)
    process.stdin.flush()
    time.sleep(2)

    process.stdin.write(password)
    process.stdin.flush()
    time.sleep(2)

    process.stdin.write(proname)
    process.stdin.flush()
    time.sleep(2)

    # 关闭标准输入文件对象
    process.stdin.close()

    # 等待命令行程序结束
    #process.wait()
    #把输出结果存储起来
    result, errors = process.communicate()
    #打印输出结果
    print(result)
auto_input_command_line()