pythonstringbashformat-stringpxssh

Python pxssh sendline string splitting and sending two lines


This is my first question here, and I'm far from professional coder, but I have been researching and didn't found any similar problem to this... I stated in the title which is pxssh realted, but in fact applies to many otehr cases seems. The problem arise when I try to format a string in order to send a line via pxssh, if I try to append fragments to the string to make the full line, instead of appending them in the correct order, the order changes and the las fragment appears in the beginning of the string. I will show the kind of string I'm trying to format, because I think is related with the character /"

sed -i -e "s/.SringInLineIWantReplace./StringIWantToPutInstead+StringFromFunctionInput1+.StringFromFunctionInput2/" FileIWantToEdit

My code looks something like this I rephrased for reproduce the error, it's curious how only happens to format incorrectly the line when I use as input the output from the function which get the Hostname, maybe some scape characters which I don't see or some magic of that kind?:

from pexpect import pxssh
import getpass

def login(hostname):
    try:
        s.login (hostname, username, password)
    except (pxssh.ExceptionPxssh, e):
        print ("pxssh failed on login.")
        print (str(e))

def logout():
    s.logout()

def MyFunction(StringFromFunctionInput1,StringFromFunctionInput2):
    line=("sed -i -e {}{}.{}{}")
    completeline=(line.format('"s/.*SringInLineIWantReplace.*/StringIWantToPutInstead',StringFromFunctionInput1,StringFromFunctionInput2,'/" FileIWantToEdit'))
    return(completeline)

def GetHostname():
    s.sendline ("hostname")
    s.prompt()
    ComputerName=(((s.before).decode("utf-8")).split("\n"))[1]
    return(ComputerName)

username = "youruser"
password = "yourpass"
address="192.168.9.100"
print(address)
s = pxssh.pxssh()
login(address)
input2=str(GetHostname())
print(MyFunction("Hi",input2))
logout()
s.close()

I tried to format the sendline string in several ways, but always happens the same, when I look into the bash history of the target host, i see how pxssh sent two lines. Hope someone can help, I'm sure it's possible to get same result using other code, but now I'm just curious about which kind of magic is behind this :S

Thanks in advance!


Solution

  • SIDENOTE1: You have a lot of extra parentheses in your code which I'm not going to reproduce in the answer. You don't need to surround an object with parentheses to call its methods/

    SIDENOTE2: It's not good practice to CapWords variable names. Only class names and type variable names should use this naming stype.


    You need to strip both the newline and the carriage return from the pyexpect response.

    The following should do it:

    computername = s.before.decode('utf-8').split('\r\n')[1]