openssh-rust / openssh

Scriptable SSH through OpenSSH in Rust
Apache License 2.0
232 stars 35 forks source link

Is there any way to set the current directory when executing command in a session #140

Open agjini opened 7 months ago

agjini commented 7 months ago

I'm executing remote commands through a Session using Session::command()

But I don't find a way to set the current directory for a given command. Even the cd command does not keep the directory changed for subsequent commands.

I am looking for something like std::process::Command::current_dir() method.

Is there any way to do this ?

NobodyXu commented 7 months ago

You can change the .ssh/config by using tempfile to create a temporary one and try something like:

Host myhost
  HostName IP
  User ubuntu
  IdentityFile ~/.ssh/id_rsa
  RemoteCommand cd /path/to/directory; $SHELL -il
agjini commented 7 months ago

Thanks for the idea. But it's such a manipulation before connecting a session. And the whole session is bound to this directory.

I've read in the source code that openssh doesn't support setting current directory (yet ?) :

command.rs:67

as only underlying shell support it. But is there a way to enable it on case bash for example is present on the remote host?

Thanks for your light

NobodyXu commented 7 months ago

Thanks for the idea. But it's such a manipulation before connecting a session. And the whole session is bound to this directory.

You can specify an alternative ssh config using SessionBuilder, before connecting.

You can then use crate tempfile to create a named temp file and write the ssh config into it, then pass it to SessionBuilder::config_file

I've read in the source code that openssh doesn't support setting current directory (yet ?)

No, AFAIK ssh doesn't support such option.

as only underlying shell support it. But is there a way to enable it on case bash for example is present on the remote host?

You could write a bash script, or use Session::shell