使用 pexpect 将脚本进程发送到后台

问题描述

我正在尝试编写脚本以更轻松地连接到 VPN。我希望脚本使用用户输入并通过 openvpn 连接到 vpn 端点,打印用户的进程 ID,然后继续在后台运行但将用户返回到 shell。我尝试了 child.close(force=False)os.fork() 和其他一些东西,但没有任何运气。我正在使用的代码如下。非常感谢任何建议!

import getpass
import os
import pexpect
import random
import subprocess
import sys

country = sys.argv[1] if len(sys.argv) > 1 else 'US'

print('Connecting to VPN through ' + country)

vpns=subprocess.run(['ls','/etc/openvpn/'],capture_output=True).stdout.decode().split('\n')
matching_vpns=filter(lambda vpn: vpn[:2].lower() == country.lower(),vpns)

chosen_vpn = random.choice(list(matching_vpns))
print('Connecting to ' + chosen_vpn + '\n')

child = pexpect.spawnu('sudo openvpn /etc/openvpn/'+chosen_vpn)

child.expect('Enter Auth Username:')
username = input('Enter Auth Username: ')
child.sendline(username)
child.expect('Enter Auth Password:')
password = getpass.getpass('Enter Auth Password: ')
child.sendline(password)

child.logfile_read = sys.stdout
while True:
    try:
        child.expect('\n',timeout=None)
        if 'Initialization Sequence Completed' in child.before:
            print("\nSuccessfully connected to " + chosen_vpn)
            print("To stop VPN,run 'sudo pkill -9 -P " + str(child.pid) + "'")
            break
    except pexpect.EOF:
        break

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)