The right way to send cqlsh command via ssh using PYTHON

Viewed 73

I tried with PYTHON to send cqlsh command via ssh and keep getting errors like

  1. no viable alternative at input ':'

  2. dsecqlsh.py not valid port

...

and I searched over internet including stack overflow, none gives the answer.

def sshRemoteCmd(user,host,cmd):
    import subprocess
    import re
    x = subprocess.Popen("ssh {user}@{host} {cmd}".format(user=user, host=host, cmd=cmd), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
    result=''

    if not x:
        result = 'error'
    else:
        for item in x:
            result += item.decode('ascii')
    return result

cmd = f'''cqlsh -e "select * from MYTABLE where userid='12345';"'''
print(cmd)
result = sshRemoteCmd('root','hosts', cmd)
print(result)
1 Answers

After the all the tricks I tried, here the right answer

  1. add localhosts and port number in the cqlsh cmd like
cqlsh localhosts 9042
  1. add double quote to wrap the whole command

  2. double escape the quote with \"

here's the final right code

def sshRemoteCmd(user,host,cmd):
    import subprocess
    import re
    x = subprocess.Popen("ssh {user}@{host} {cmd}".format(user=user, host=host, cmd=cmd), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
    result=''

    if not x:
        result = 'error'
    else:
        for item in x:
            result += item.decode('ascii')
    return result

cmd = f'''"cqlsh localhost 9042 -e \\"select * from MYTABLE where userid='1234';\\""'''
print(cmd)
result = sshRemoteCmd('root','hosts', cmd)
print(result)
Related