Adrian
Adrian

Reputation: 159

How to open a new console from python script and be able to manage it

I am writing a script that needs to be able to open a separate console window and read and write to it(on Windows). I want to use telnet and ssh from new consoles and the main console use as a manager

Right now i was trying thoes things:

main file

import subprocess as sp
from getpass import getpass
import telnetlib
import multiprocessing as mp
import os

def run(command):
    cmd = sp.Popen(command.split(), sp.PIPE)
    com, err = cmd.communicate()
    print(com,err)

if __name__ == "__main__":
    login = input("Podaj login: ")
    password = getpass()

    ip = "10.74.119.252"
    command = f"python LogInConsol.py {ip} {login} {password}"

    process = mp.Process(target=run, args= (command,))
    process.start()

LogInConsol file

import telnetlib
import subprocess as sb
import sys

argv = sys.argv
ip = argv[1]
login = argv[2]
pw = argv[3]

# tn = telnetlib.Telnet(host=ip, port= 23)
# tn.read_until(b"login: ")
command = f"cmd.exe start /k telnet {ip}"
cmd = sb.run(command.split(),sb.PIPE)
com, err = cmd.communicate()

But the behavior is such that everything happens in main consol window(from which i start program)

UPDATE

This started to work as i wanted it to.

Main.py

from subprocess import Popen, PIPE, CREATE_NEW_CONSOLE
from getpass import getpass
import telnetlib
import multiprocessing as mp
import threading as th

def run(command):
    cmd = Popen(command, PIPE, creationflags=CREATE_NEW_CONSOLE)
    com, err = cmd.communicate()
    print(com,err)
if __name__ == "__main__":
    mp.freeze_support()
    login = input("Podaj login: ")
    password = getpass()
    ip = "10.10.10.10"
    command = f"python LogInConsol.py {ip} {login} {password}"
    process = mp.Process(target=run, args= (command,))
    process.start()
    input("Wait ")

LogInConsol.py

import telnetlib
import subprocess as sp
import sys


argv = sys.argv
ip = argv[1]
login = argv[2]
pw = argv[3]


print(argv)
tn = telnetlib.Telnet(host=ip,port=23)
red = tn.read_until(b"username: ")
print(red)

Upvotes: 0

Views: 6937

Answers (2)

GaloisGirl
GaloisGirl

Reputation: 1516

Could this be a case of the XY problem? You need to connect via telnet or ssh, but do you really need that console in between?

You can make telnet connections in python using telnetlib and ssh ones with paramiko.

Upvotes: 1

Brandon Bailey
Brandon Bailey

Reputation: 811

Could try wshshell:

1. pip install pywin32-221-cp36-cp36m-win_amd64.whl
2. python.exe pywin32_postinstall.py -install  (DOS command line)

in script:

   import win32com.client
   WshShell = win32com.client.Dispatch("WScript.Shell")
   WshShell.run("cmd")

Upvotes: 1

Related Questions