Identifying local processes and associated ports with python - python

Does python or any linux/unix languages have a library which allows it to find ports available on the localhost based on processes name?
I would like to identify all associated ports with the service name ssh.
lsof, netstat ps or grep don't seem the most efficient options.

This got me what I needed, thank you.
ss -l -p -n | grep ",pid=`pgrep ssh`," | grep ::: | cut -d : -f 4

Related

Finding on which port a given server is running within python program

I am developing a python 3.11 program which will run on a few different servers and needs to connect to the local Redis server. On each machine the latter might run on a different port, sometimes the default 6379 but not always.
On the commandline I can issue the following command which on both my Linux and MacOS servers works well:
(base) bob#Roberts-Mac-mini ~ % sudo lsof -n -i -P | grep LISTEN | grep IPv4 | grep redis
redis-ser 60014 bob 8u IPv4 0x84cd01f56bf0ee21 0t0 TCP *:9001 (LISTEN)
What's the better way to get the running port using python functions/libraries?
What if you run your commands within a py script using the os library:
import os
cmd = 'ls -l' <-- change the command you want to run
os.system(cmd)
or else you could also use subprocess library as well:
import subprocess
print(subprocess.check_output(['ls', '-l']))

Killing a process within a python script running on linux

I have Raspbian as the linux distro running on my RPI. I've setup a small socket server using twisted and it receives certain commands from an iOS app. These commands are strings. I started a process when I received "st" and now I want to kill it when i get "sp". This is the way I tried:
Imported OS
Used os.system("...") //to start process
os.system("...") // to kill process
Lets say the service is named xyz.
This is the exact way I tried to kill it:
os.system('ps axf | grep xyz | grep -v grep | awk '{print "kill " $1 }' | sh')
But I got a syntax error. That line runs perfectly when I try it in terminal separately. Is this a wrong way to do this in a python script? How do I fix it?
You will need to escape the quotes in your string:
os.system('ps axf | grep xyz | grep -v grep | awk \'{print "kill " $1 }\' | sh')
Or use a triple quote:
os.system('''ps axf | grep xyz | grep -v grep | awk '{print "kill " $1 }' | sh''')
Alternatively, open the process with Popen(...).pid and then use os.kill()
my_pid = Popen('/home/rolf/test1.sh',).pid
os.kill(int(my_pid), signal.SIGKILL)
Remember to include a shebang in your script (#!/bin/sh)
Edit:
On second thoughts, perhaps
os.kill(int(my_pid), signal.SIGTERM)
is probably a better way to end the process, it at least gives the process the chance to close down gracefully.

How to check if NTP server is running on a Linux machine by a python script

I need to get IP address of a machine and check if NTP server is running on that. In addition, if it is not running, just start it.
I checked several posts and non of them worked for me.
You can use fabric for this. It's great! Here's a quick and dirty way:
from fabric.api import run
def restart_ntp_if_not_running():
run('if [[ $(netstat -p tcp -n | grep [your ip].123 | grep ESTABLISHED) ]]; then true; else [your command to restart here]; fi;')
The execute this like:
fab -H [host name] restart_ntp_if_not_running

port conflict between Hadoop and python

I am installing Hadoop 2.5.0 on a Ubuntu 12.04 cluster, 64-bit. At the end of the instructions I type $ jps on the master node and do not get a NameNode. I checked the Hadoop logs and found:
BindException error stating :9000 is already in use.
$ netstat -a -t --numeric-ports -p | grep :9000 returns that python is listening on this port. It appears I need to move python 2.7 to another port. How do I move python?
Followed the command below, the pid=2346.
$ ps -p 2346
PID TTY TIME CMD
2346 ? 01:28:13 python
Tried second command:
$ ps -lp 2346
F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD
4 S 0 2346 1 0 80 0 - 332027 poll_s ? 01:28:30 python
more detail:
$ ps -Cp 2346
PID TTY STAT TIME COMMAND
2346 ? Ssl 88:34 /usr/lib/cmf/agent/build/env/bin/python /usr/lib/cmf/agent/src/cmf/agent.py --package_dir /usr/lib/cmf
It appears a failed Cloudera Hadoop distribution installation has not been removed. It installed python 2.7 automatically. Not sure what else is automatically running. Will attempt to uninstall python 2.7.
To be clear a program written in python is using port 9000 and not python2.7 itself.
You need to track down this program and then work out how to config it to listen on a different port. You could use this command to get the full details of the process listening on port 9000
netstat -a -t --numeric-ports -p | grep :9000 | awk '{print $7}' | sed -e 's/\/.*//' | xargs echo ps -lp
It appears Cloudera installed python 2.7. This was removed / replace with python 3.2.
The $jps command on Hadoop now returns the expected results including NameNode.

How to kill multiple tornado processes at one time?

I used nohup python *.py & to run my tornado web service, and 8 processes started.
.
However, it is really annoying killing my tornado processes. I have to ues kill -3 pid 8 times to finally turn down my service. So I want to know how can I kill the 8 processes at one time in my bash? Thanks.
I tried killall python, but it is dangerous when there is other python process running.
#Viktor suggest me to use pkill -P <parent> and it works in my Ubuntu. But in Centos, 'pkill' doesn't work. So how can I 'pkill' the processes in Centos? Thanks.
This depends on your environment a bit.
But you may want to look into pkill -P <parent>, which kills everything with the same parent pid.
Maybe :
ps aux | grep -e 'python spam.py' | grep -v grep | awk '{print $2}' | xargs -i kill {}
Killing the parent process, that is the one with smallest PID should do the job, like kill -15 18054 in your ps example. Also, you could do some grep magic, like:
for i in `ps waux | grep "python spam.py" | awk '{ print $2 }'`; do kill -15 ${i}; done

Categories