Python Pexpect and Check Point Gaia Expert Mode - python

I administer a few Check Point Firewalls at work that run on the Gaia operating system. Gaia is a hardened, purpose-built Linux OS using the 2.6 kernel.
I am a novice at Python and I need to write a script that will enter "expert mode" from the clish shell. Entering expert mode is similar to invoking su as it gives you root privileges in the BASH shell.
Clish is a Cisco like custom shell made to ease OS configuration changes. I saw a similar discussion at pexpect and ssh: how to format a string of commands after su - root -c, but people responding recommended sudo.
This is not an option for me as sudo is not supported by the OS and if you were to install it, clish would not recognize the command. The goal of my script would be to SSH to the device, login, invoke expert mode, then run grep admin /etc/passwd and date. Again, sudo is not an option.

clish does not support SSH. But you can change the shell of your user to /bin/bash instead of /etc/clish.sh
set user <myuser> shell /bin/bash
save config

Related

How to use python to write wsl shell command? [duplicate]

I'm on Windows using PowerShell and WSL 'Ubuntu 20.04 LTS'. I have no native Linux Distro, and I cant use virtualisation because of nested device reasons.
My purpose is to use a Windows Python script in PowerShell to call WSL to decrypt some avd-snapshots into raw-images. I already tried os.popen, subprocess.Popen/run/call, win32com.client, multiprocessing, etc.
I can boot the WSL shell, but no further commands are getting passed to it. Does somebody know how to get the shell into focus and prepared for more instructions?
Code Example:
from multiprocessing import Process
import win32com.client
import time, os, subprocess
def wsl_shell():
shell = win32com.client.Dispatch("wscript.shell")
shell.SendKeys("Start-Process -FilePath C:\\Programme\\WindowsApps\\CanonicalGroupLimited.Ubuntu20.04onWindows_2004.2021.825.0_x64__79rhkp1fndgsc\\ubuntu2004.exe {ENTER}")
time.sleep(5)
os.popen("ls -l")
if __name__ == '__main__':
ps = Process(target = wsl_shell)
ps.start()
There are a few ways of running WSL scripts/commands from Windows Python, but a SendKeys-based approach is usually the last resort, IMHO, since it's:
Often non-deterministic
Lacks any control logic
Also, avoid the ubuntu2004.exe (or, for other users who find this, the deprecated bash.exe command). The much more capable wsl.exe command is what you are looking for. It has a lot of options for running commands that the <distroname>.exe versions lack.
With that in mind, here are a few simplified examples:
Using os.system
import os
os.system('wsl ~ -e sh -c "ls -l > filelist.txt"')
After running this code in Windows Python, go into your Ubuntu WSL instance and you should find filelist.txt in your home directory.
This works because:
os.system can be used to launch the wsl command
The ~ tells WSL to start in the user's home directory (more deterministic, while being able to avoid specifying each path in this case)
wsl -e sh runs the POSIX shell in WSL (you could also use bash for this)
Passing -c "<command(s)>" to the shell runs those commands in the WSL shell
Given that, you can pretty much run any Linux command(s) from Windows Python. For multiple commands:
Either separate them with a semicolon. E.g.:
os.system('wsl ~ -e sh -c "ls -l > filelist.txt; gzip filelist.txt')
Or better, just put them all in a script in WSL (with a shebang line), set it executable, and run the script via:
wsl -e /path/to/script.sh
That could even by a Linux Python script (assuming the correct shebang line in the script):
wsl -e /path/to/script.py
So if needed, you can even call Linux Python from Windows Python this way.
Using subprocess.run
The os.system syntax is great for "fire and forget" scripts where you don't need to process the results in Python, but often you'll want to capture the output of the WSL/Linux commands for processing in Python.
For that, use subprocess.run:
import subprocess
cp = subprocess.run(["wsl", "~", "-e", "ls", "-l"], capture_output=True)
print(cp.stdout)
As before, the -e argument can be any type of Linux script you want.
Note that subprocess.run also gives you the exit status of the command.

How do I get a python script to run a command shell in Windows (10) where it opens in a program specific location?

I need to run commands in command prompt but they only work when the command prompt is set at a particular location in the system. I need the following commands to run in a python script:
import os
os.system("set OMP_NUM_THREADS=2")
os.system("explorer.exe /e,::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"#
os.system("cd C:\CFD\crit_vel_01_02")
os.system("mpiexec -n 9 FDS crit_vel_01_02.fds")
os.system("PAUSE")
the system does not recognise the command
os.system("mpiexec -n 9 FDS crit_vel_01_02.fds")
unless this is run in the command shell which is installed on installation of the program "fds" which is a fire dynamics simulator. I appreciate this seems quite specific to the program but I am assuming there is some generic way that python can run command shell from a different location/with different settings.
The shortcut to the command prompt is called CMDfds and is installed in:
"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\FDS6"
in the properties the target in the shortcut tab is:
"C:\Windows\System32\cmd.exe /k fdsinit"
Not sure it will work but you can give a try at subprocess.run with shell=True.
If shell is True, the specified command will be executed through the shell. This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want convenient access to other shell features such as shell pipes, filename wildcards, environment variable expansion, and expansion of ~ to a user’s home directory.
Also try running the python script from the fds command shell. It seems to be initializing stuff in the shell.
The trouble with running programs with system commands is that they often have a different shell environment. In order to prevent problems arising from this it's a good idea to use absolute paths. In your case:
os.system("mpiexec -n 9 FDS crit_vel_01_02.fds")
should be changed to:
os.system("/absolute/path/to/mpiexec -n 9 FDS crit_vel_01_02.fds")

How can use Unix on Windows 10 by Python?

I'm learning Python by the book 'Think Python.'
My computer's OS is Windows 10.
I tried using os.popen ('14.8 Pipes' in http://www.greenteapress.com/thinkpython/html/thinkpython015.html) but the book provides an example on Unix.
I want to run Unix on Python script out of curiosity.
I already installed Git bash and Virtual box, but I don't know how to connect and to use Python.
The example provided by the book is:
14.8 Pipes
Most operating systems provide a command-line interface, also known as
a shell. Shells usually provide commands to navigate the file system
and launch applications. For example, in Unix you can change
directories with cd, display the contents of a directory with ls, and
launch a web browser by typing (for example) firefox.
Any program that you can launch from the shell can also be launched
from Python using a pipe. A pipe is an object that represents a
running program.
For example, the Unix command ls -l normally displays the contents of
the current directory (in long format). You can launch ls with
os.popen1:
>>> cmd = 'ls -l'
>>> fp = os.popen(cmd)
It appears you are getting tripped up converting the ls command which lists directory contents on *nix to a Windows command. If you search for "what is the windows version of ls" in a search engine, you will discover that Windows provides similar functionality through dir. For more useful conversions check out the conversion table on lemonda.net.
Changing the code to
>>> cmd = 'dir' and calling it via
>>> fp = os.popen(cmd)
Should enable the example to run on Windows.
if you have the latest update of windows 10 you can use Ubuntu, a version of Linux, from your command prompt by just typing the word 'bash' and waiting on it to download some files. if you see a $ at the end of your command line you got it. after that just type 'sudo apt-get install python' and enter your windows password when it asks for your password hit the 'Y' key when it asks if you are sure. then you should be able to go from the book from there.
EDIT: I believe you have to run cmd as administrator to install bash. You also may have to enable it by hitting the 'windows key + r' to open the run window then type 'appwiz.cpl to open the uninstall window and then click the button on the left of the screen that says 'Turn Windows features on or off', then wait for that to load and then go check the box by 'Windows Subsystems for Linux (Beta)' and then trying to type 'bash' in an elevated cmd prompt.

How to provide input to shell from python?

I am running my python in ubuntu and trying to make a script that communicates with the shell. My script is simple
import os
os.system('sudo su - xyz')
when I run the script and try to login xyz, it asks for the password in my shell. But how do I send the password via the python script and just login.? Is there a better way to do this ?
Piping a hardcoded password into stdin so that you don't have to input it for a command which requires sudoer privileges is overthinking it (in addition to being highly insecure).
Just assume in your Python script that you are root (i.e. don't execute commands with sudo).
import os
os.system('su - xyz')
Then launch your Python script with sudo.
$ sudo python foo.py
Unless you have some weird requirements, this is the most natural way to do it.
You can try piping the password into the commandline string.
NOTE: This is VERY insecure. Anyone has access to your python script will know your password and can get a hold of your system.
import os
password = 'ABCDEFG'
os.system('echo {} | sudo -S su - xyz'.format(password))
EDIT: Note adding echo and -S to sudo, so it can accept password from a pipe

How to use python subprocess.check_output with root / sudo

I'm writing a Python script that will run on a Raspberry that will read the temperature from a sensor and log to Thingspeak. I have this working with a bash script but wan't to do it with Python since it will be easier to manipulate and check the read values. The sensor reading is done with a library called loldht. I was trying to do it like this:
from subprocess import STDOUT, check_output
output = check_output("/home/pi/bin/lol_dht22/loldht", timeout=10)
The problem is that I have to run the library with sudo to be able to access the pins. I will run the script as a cron. Is it possible to run this with sudo?
Or could I create a bash script that executes 'sudo loldht' and then run the bash script from python?
I will run the script as a cron. Is it possible to run this with sudo?
You can put python script.py in the cron of a user with sufficient privileges (e.g. root or a user with permissions to files and devices in question)
I don't know which OS you're using, but if Raspbian is close to Debian, there is no need for sudo or root, just use a user with sufficient permissions.
It seems I can also do this check_output check_output(["sudo", "/home/pi/bin/lol_dht22/loldht", "7"], timeout=10)
Sure but the unix user that's going to invoke that Python script will need the sudo privilege (Otherwise can't call the sudo from subprocess). In which case you might as well do as above, run the cron from a user with the required permissions.
You can run sudo commands with cron. Just use sudo crontab -e to set the cron and it should work fine.
You should very careful with running things as root. Since root has access to everything, a simple error can potentially render the system unusable.
The proper way to have access to the hardware as a normal user is to change the permissions on the required device files.
It seems that the utility you mention uses the WiringPi library. Some digging in the source code indicates that it uses the /dev/gpiomem (or /dev/mem) devices.
On raspbian, device permissions are set with udev. See here and also here.
You could give every user access to /dev/gpiomem and other gpio devices by creating a file e.g. /etc/udev/rules.d/local.rules and putting the following text in it:
ACTION=="add", KERNEL=="gpio*", MODE="0666"
ACTION=="add", KERNEL=="i2c-[0-9]*", MODE="0666"
The first line makes the gpio devices available, the second one I2C devices.

Categories

Resources