Executing sudo commands on remote machine via jumpssh in python - python

I'm working on a python script that can execute commands on a remote host via ssh and jumpbox. I can do this just fine using the jumpssh module as long as the command is unpriviledged. It's when I need to do a sudo commands where I run into problems as the command just hangs, presumably waiting for me to enter my sudo password. I've tried to google this and came up empty.
Here is what I've did to test this out:
c:\siggi>python
Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import jumpssh
>>> gw = jumpssh.SSHSession("jumpbox","siggi").open()
>>> remote = gw.get_remote_session("supergeeks")
>>> remote.get_cmd_output("whoami")
'siggi'
>>> remote.get_cmd_output("hostname")
'supergeeks'
>>> remote.get_cmd_output("ls")
'exp.xlsx agent_3.3.0.10614-10774_amd64.deb Status.py'
>>> remote.get_cmd_output("ls /")
'bin home\t lib32\t media root swapfile var\r\nboot initrd.img lib64\t mnt\t run sys\t vmlinuz\r\ndev initrd.img.old libx32\t opt\t sbin tmp\t vmlinuz.old\r\netc lib\t lost+found proc\t srv usr'
>>> remote.get_cmd_output("ls /root")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\SigurðurGísliBjarnas\AppData\Roaming\Python\Python310\site-packages\jumpssh\session.py", line 431, in get_cmd_output
return self.run_cmd(cmd=cmd, **kwargs).output
File "C:\Users\SigurðurGísliBjarnas\AppData\Roaming\Python\Python310\site-packages\jumpssh\session.py", line 399, in run_cmd
raise exception.RunCmdError(exit_code=exit_code,
jumpssh.exception.RunCmdError: Command (ls /root) returned exit status (2), expected [0]: ls: cannot open directory '/root': Permission denied
>>> remote.get_cmd_output("sudo ls /root")

Related

having issues with pykd (pykd.DbgException: Call IDebugClient::GetOutputCallbacks failed HRESULT 0x80010107)

I'm working with pykd and am able to connect it with my debugger (windbg) but for some reason I'm unable to process any command with pykd.dbgCommand not sure what the issue is as I've tried multiple methods to try and resolve the issue:
Reinstall pydk + python
tried on python2.7, python3.5, python3.8
tried a different system + different debug session
when I tried to run the command on the windbg session it was able to produce the results but somehow it's now able to do that from python console.
pykd.dbgCommand("!analyze -v")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
pykd.DbgException: Call IDebugClient::GetOutputCallbacks failed
HRESULT 0x80010107
any help would be appreciated.
thanks to everyone answering in advance.
I tried to run dbgCommand('!analyze -v') with three different dump from python REPL:
usermode native dump: OK
kernel mode dump: OK
managed app dump:
0:000> !py
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> dbgCommand('analyze -v')
Traceback (most recent call last):
File "<console>", line 1, in <module>
pykd.DbgException: Call IDebugControl::ExecuteWide failed
HRESULT 0x80040205
Then I run this script:
import pykd
a = pykd.dbgCommand('!analyze -v')
print(a)
this script works OK with all of these dump.
I believe there is a bug. I've opened an issue:
https://githomelab.ru/pykd/pykd-ext/-/issues/15
Can you provide a dump which reproduce the bug to the pykd issues tracker.

FileNotFoundError: [Errno 2] No such file or directory: 'netsh'

This is my python Code to see the Devices connected to my WIFI:
import subprocess
meta_data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles'])
data = meta_data.decode('utf-8', errors="backslashreplace")
data = data.split('\n')
names = []
for i in data:
if "All Users Profiles" in i:
i = i.split(":")
i = i[1]
i = i[1:-1]
names.append(i)
print("Systems Connected To Your WIFI ARE ")
print()
for name in names:
print(name)
AND this is the error I keep getting after i run the code:
FileNotFoundError: [Errno 2] No such file or directory: 'netsh'
You need to call it through the shell using cmd.exe /c or by passing shell=true into check_output. The subprocess package does not run in a shell by default on Windows.
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.check_output(["dir"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
...
FileNotFoundError: [WinError 2] The system cannot find the file specified
>>> subprocess.check_output(["cmd.exe","/c","dir"])
b' ... '
>>> subprocess.check_output(["dir"], shell=True)
b' ... '
This is only something you need to do on Windows.
Python 3.8.0 (default, Oct 28 2019, 16:14:01)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.check_output(["ls"])
b' ... '

How do i upload tinkergraph into python/gremlin?

I am trying to use gremlin in python. I imported the following:
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.structure.graph import Graph
from gremlin_python import statics
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.strategies import *
from gremlin_python.process.traversal import *
import asyncio
statics.load_statics(globals())
When i run this:
graph = TinkerGraph.open()
graph.io(graphml()).readGraph('air-routes.graphml')
i get the following error:
NameError: name 'TinkerGraph' is not defined
How do i resolve this?
There is no TinkerGraph in Python. In gremlin-python you only get a reference to a graph remotely on a server and that might be a TinkerGraph or something else. If you want to load data that way, you must issue that command as a script through a Client instance:
client = Client('ws://localhost:45940/gremlin', 'g')
client.submit("graph.io(graphml()).readGraph('air-routes.graphml');[]").all().result()
where "graph" in that script is a Graph instance that already exists on the server (and is likely empty). If you're using Gremlin Server, you might consider doing that loading separately as part of Gremlin Server startup as well and then just using gremlin-python to query that data. That would probably be best in this example as the data would just be present when the server is started.
Note that in 3.4.0, we introduce the io() step which will be part of gremlin-python directly at which point you will be able to directly do:
g.io('air-routes.xml').read()
in native python and it will just work (again, the Graph instance must be defined remotely) though the file must be readable by the server.
Here's my working example in the Python shell for submitting a script, first with the tornado error and then without:
$ env/bin/python
Python 3.4.3 (default, Nov 28 2017, 16:41:13)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from gremlin_python.driver.client import Client
>>> client = Client('ws://localhost:8182/gremlin', 'g')
>>> client.submit("g.V()").all().result()
Traceback (most recent call last):
File "/home/smallette/git/apache/incubator-tinkerpop/gremlin-python/target/python3/gremlin_python/driver/client.py", line 51, in __init__
from gremlin_python.driver.tornado.transport import (
File "/home/smallette/git/apache/incubator-tinkerpop/gremlin-python/target/python3/gremlin_python/driver/tornado/transport.py", line 19, in <module>
from tornado import ioloop, websocket
ImportError: No module named 'tornado'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/smallette/git/apache/incubator-tinkerpop/gremlin-python/target/python3/gremlin_python/driver/driver_remote_connection.py", line 45, in __init__
password=password)
File "/home/smallette/git/apache/incubator-tinkerpop/gremlin-python/target/python3/gremlin_python/driver/client.py", line 54, in __init__
raise Exception("Please install Tornado or pass"
Exception: Please install Tornado or passcustom transport factory
>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
>>> exit()
$ env/bin/pip install tornado
Collecting tornado
Collecting backports-abc>=0.4 (from tornado)
Using cached https://files.pythonhosted.org/packages/7d/56/6f3ac1b816d0cd8994e83d0c4e55bc64567532f7dc543378bd87f81cebc7/backports_abc-0.5-py2.py3-none-any.whl
Installing collected packages: backports-abc, tornado
Successfully installed backports-abc-0.5 tornado-5.1.1
smallette#ubuntu:~/git/apache/incubator-tinkerpop/gremlin-python/target/python3$ env/bin/python
Python 3.4.3 (default, Nov 28 2017, 16:41:13)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from gremlin_python import statics
>>> client = Client('ws://localhost:8182/gremlin', 'g')
>>> client.submit("g.V()").all().result()
[v[0]]

Inspect lambda code from Python interpreter

this simple python program that is extracted from more complex codebase:
#insp.py
import inspect
L = lambda x: x+1
print("L(10)=" + str(L(10)))
code = inspect.getsource(L)
print(code)
works if i run it from the command line as:
$ python insp.py
If I copy and paste each line in the python interpreter it fails:
d:\>python
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import inspect
>>> L = lambda x: x+1
>>> print("L(10)=" + str(L(10)))
L(10)=11
>>> code = inspect.getsource(L)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "d:\Users\Cimino\AppData\Local\Programs\Python\Python35-32\Lib\inspect.py", line 944, in getsource
lines, lnum = getsourcelines(object)
File "d:\Users\Cimino\AppData\Local\Programs\Python\Python35-32\Lib\inspect.py", line 931, in getsourcelines
lines, lnum = findsource(object)
File "d:\Users\Cimino\AppData\Local\Programs\Python\Python35-32\Lib\inspect.py", line 762, in findsource
raise OSError('could not get source code')
OSError: could not get source code
Note that using IPython instead of the plain Python interpreter, it works!
Does anybody know why?
I use Python 3.5 32 bits under Windows7.
It works in IPython because it caches each and every command you enter there using linecache module.
For example:
$ ipy ## Equivalent to ipython --classic
Python 2.7.10 (default, Jul 30 2016, 18:31:42)
Type "copyright", "credits" or "license" for more information.
IPython 3.0.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
>>> print a
Traceback (most recent call last):
File "<ipython-input-1-9d7b17ad5387>", line 1, in <module>
print a
NameError: name 'a' is not defined
Notice the <ipython-input-1-9d7b17ad5387> part here, this is something specific to IPython. In normal Python shell you would see <stdin>:
$ python
Python 2.7.10 (default, Jul 30 2016, 18:31:42)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
Now let's run your code:
>>> import inspect
>>> L = lambda x: x+1
>>> code = inspect.getsource(L)
Time to find out the filename related to L:
>>> L.func_code.co_filename
'<ipython-input-2-0c0d6f325784>'
Now let's see if we have the source in linecache.cache for this file:
>>> import linecache
>>> linecache.cache[L.func_code.co_filename]
(18, 1481047125.479239, [u'L = lambda x: x+1\n'], '<ipython-input-2-0c0d6f325784>')
So, using this information IPython is able to find the required source but Python shell doesn't because it is not storing any.
The related details about how inspect gets the source can be found in getsourcefile and findsource functions in the source code.

os.tmpfile() doesn't work under windows?

I'm trying to use generateDS under windows, which uses os.tmpfile. Unfortunately, os.tmpfile doesn't work for me:
(oneclickcos) C:\Users\Marcin\Documents\oneclickcos\xsd>python
Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.tmpfile()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 13] Permission denied
>>>
I've got all my temp directories set with full control for everyone, so that shouldn't be the problem.
What could be causing this?
Run the script as administrator (right click on the script and select 'run as administrator'), the script lacks the permissions to execute os.tmpfile().
Edit:
As I see you're using the interpreter, simply run the interpreter as administrator. If you're accessing it though a terminal, running the terminal as administrator should be sufficient.
As Griffin pointed out the problem is that the os.tmpfile() tries to create a file in the root directory. If you don't like to run the script as administrator you can use os.tmpnam() and handle the file yourself.
Warning: Use of tmpnam() is vulnerable to symlink attacks

Categories