Python Forum

Full Version: Trying to convert my Expect/bash to Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Good Morning,

I am trying to gain some python knowledge and convert scripts Ive written in expect and bash.
I do not have permission to load modules so Netmiko/paramiko and Pexpect/pxxsh is not available to me.
I will need to find solutions using default modules where possible.

I often need to connect to network devices. The following works but Im not all that sure what is happening.
I found this script online.
My question is .. once I log in .. how do I execute commands on the network device.
Im also reviewing the subprocess module. I dont quite understand whats going on with the ClientSocket assignment. and I also dont understand whats going on with following portion of the ssh execution.



{0}".format(port).split()
In bash, I can use set -x to see the code execute. Is there a way I can do this in python ?
I am on a Centos 6 V .. old and crusty Python 2.6.4


#!/usr/bin/python
import socket
import subprocess

ClientSocket = socket.socket()
try:
    ClientSocket.connect(("10.10.10.10", 22))
    port = 22
except socket.error:
    ClientSocket.connect(("10.10.10.10", 23))
    port = 23
finally:
    command = "sshpass -pMYPASSWORD ssh -t -t [email protected] -p {0}".format(port).split()
    subprocess.call(command)
    subprocess.call("dir")
    ClientSocket.close()
Thanks for the help in advance.
Not being able to load packages is a huge problem.
But you can connect using sockets?
doesn't make sense.
Have you tried pip?
Try: pip install expect

or pip3 install expect
Yes. I do have root .. but the admin gods dont want anything loaded on the VM. Will get spanked if I do it and they find out.
You don't need root access to install packages (or at least shouldn't)
Then as user:
pip3 install expect --user
Or make first a virtual environment:

python3 -m venv env
source env/bin/activate
pip install expect
Before you run your script, you must have activated the virtual environment with
source path/to/env/bin/activate
Or you run your script with:
path/to/env/bin/python your_script.py