How to run a remote command in PuTTY after login & keep the shell running?

Solution 1:

What the -m does is, that it makes PuTTY instruct the SSH server to start that command(s) INSTEAD of a shell. So once your command finishes, so does the session.

If you want to run the shell after the cd command, you need to add it explicitly to your cmd.txt, like:

cd /my/path ; /bin/bash

Also the -m implies "nopty"/non-interactive mode. To use an interactive shell you need to override that using the -t switch.

putty.exe -ssh example.com -m "c:\path\cmd.txt" -t

Alternatively use KiTTY with its -cmd switch, that does what you want (and does not need a temporary file).

Solution 2:

You need both -t and a shell to keep the session running. When your script returns there's no shell to keep control of the session, so the server terminates the connection. You need to start tmux or a shell so the server doesn't terminate the connection when your commands stop running. But that introduces another complexity: how to show the results of your commands on the terminal.

The most naive solution I've found is to run a the commands and call a shell at the end (/bin/bash or which your host have available). This allows the results of the previous scripts to be still be read and drops you into an interactive shell. This has the limitations that you can't configure your shell session, since it would return immediately it runs whatever command you tell it to run at which point the server would terminate the session.