How can I capture the output of an nslookup command over ssh in Python?

71 views Asked by At

Hi am am automating nsupdate but I want to check if a domain exists before inserting it. It if exists I want to give a warning. The problem is that I can't seem to capture the output of a single command over ssh. It would seem logical to me if I simply did this: result = sshProcess.stdin.write("nslookup {item.domain \n")

But that does not work, I am working on a system that does not have access to internet and for that reason I can't (and am not allowed to) install packages such as Paramiko (so please don't give me that as solution I have to use built-in modules).

This is the code I have. I only showed the relevant code, the ssh connection and executing commands over ssh works fine though.

import subprocess

def connectToSSH():
    sshProcess = subprocess.Popen(["ssh", f"{env_vars[0]['value']}@{env_vars[1]['value']}"],
                               stdin=subprocess.PIPE, 
                               stdout = subprocess.PIPE,
                               universal_newlines=True,
                               bufsize=0)
    sshProcess.stdin.write("bash \n")
    sshProcess.stdin.write("nsupdate \n")
    sshProcess.stdin.write("server 127.0.0.1 \n")
    for item in AddOrUpdateRecords:
           # I want to capture this command  = nslookup but it does not work
            result = sshProcess.stdin.write("nslookup {item.domain \n")
            sshProcess.stdin.write(f"update add {item.domain} {item.ttl} {item.type} {item.destination} \n")
    sshProcess.stdin.write("send \n")
    sshProcess.stdin.write("quit \n")
    sshProcess.stdin.close()

    for line in sshProcess.stdout:
        if line == "END\n":
            break
        print(line,end="")

    #to catch the lines up to logout
    for line in  sshProcess.stdout: 
        print(line,end="")



if __name__ == "__main__":
    getEnvVars()
    connectToSSH()
    
0

There are 0 answers