1

What I actually tried to do:

Using a python script to start a nc(netcat) on a remote host using SSH. This netcat should listen for incoming TCP connections. It could be possible that no one wants to connect to the remote host so the netcat process have to be killed.

My first idea was using the PID of the nc process on the remote host and execute a simple kill [PID] command. But I was not able to get the process id from the nc process on the remote host.

What I have tried so far was using paramiko and sshpass.

My paramiko code:

    import os, sys, paramiko


    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    ssh.connect(host, username=user, password=password)
    stdin, stdout, stderr = ssh.exec_command("nc -l -p"+port+"&")
    print stdout.readlines()

Using sshpass:

    sshProcess = subprocess.Popen(["sshpass", "-p", password, "ssh", user+"@"+hostaddress, "nc", "-l", "-p", str(destPort),"&"], stdout=subprocess.PIPE, stdin=None)
    print sshProcess.stdout.read()

I tried the sshpass approach on the normal linux terminal and the pid of the netcat process was returned. But trying both approaches in a python script had the same result: the whole script was blocked instead of returning the PID. If I do not try to read the output -- that means deleting the stdout.readlines() or sshProcess.stdout.read() -- the scripts are not blocked but I also do not get the PID of the netcat process on the remote host.

I am working on a Linux machine and the remote host also runs Linux.

Pierre GM
  • 19,809
  • 3
  • 56
  • 67
  • [fabric](http://fabfile.org) might provide a more high level interface than paramiko to run command via ssh in Python. – jfs Sep 19 '12 at 09:09

1 Answers1

0

Remove "&" to execute nc synchronously with ssh -t then to kill nc just kill the subprocess (p.terminate()).

See how to stop reading the subprocess stdout on timeout.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670