如何通过调用命令文本的批处理文件在Putty窗口执行cd命令
Alright, let's break down how to get this working—launching PuTTY via a batch file and running a cd command (or any sequence of commands) from a separate text file. It's straightforward once you know the right PuTTY parameters to use.
a.bat batch file This file will handle launching PuTTY, pointing it to your remote server, and telling it to execute commands from your p.txt file. Here's the code you need:
@echo off rem Update these variables to match your setup set PUTTY_PATH="C:\Program Files\PuTTY\putty.exe" set SSH_CONNECTION="your-username@your-server-ip-or-hostname" set COMMAND_FILE="%~dp0p.txt" rem Launch PuTTY with the command file %PUTTY_PATH% %SSH_CONNECTION% -m %COMMAND_FILE%
A quick breakdown of what each line does:
@echo off: Hides command prompts from printing as the batch runsPUTTY_PATH: The full path to your PuTTY executable (adjust this if you installed PuTTY in a non-default location, likeC:\Program Files (x86)\PuTTY\putty.exefor 32-bit systems)SSH_CONNECTION: Your remote server's SSH credentials (e.g.,root@192.168.1.50oradmin@my-server.com)COMMAND_FILE: Uses%~dp0to reference the same folder asa.bat, so you can keepp.txtin the same directory without typing an absolute path
If you need to use a non-standard SSH port (not 22), add the -P parameter like this:
%PUTTY_PATH% %SSH_CONNECTION% -P 2222 -m %COMMAND_FILE%
Or if you have a saved PuTTY session, you can use that instead of the direct connection string:
%PUTTY_PATH% -load "MySavedServerSession" -m %COMMAND_FILE%
p.txt command file This is where you'll put the actual commands you want to run on the remote server. For your cd command example, it might look like this:
cd /path/to/your/target/directory # Add any other commands you want to run here, like: ls -l
Pro tip to keep the session open:
By default, PuTTY will close the window right after executing the commands in p.txt. If you want to stay logged in after the commands run, add an interactive shell command at the end:
cd /path/to/your/target/directory ls -l bash -i # Use `sh -i` instead if your remote system uses sh instead of bash
- Make sure
p.txtis saved with ANSI or UTF-8 (without BOM) encoding—PuTTY might fail to read commands if the encoding is off. - Verify that your PuTTY path is correct; if you get a "file not found" error, double-check this variable.
- Ensure your remote server allows password-based SSH login (or that you've set up key-based auth) so PuTTY can connect without manual input.
内容的提问来源于stack exchange,提问作者Tavleen Kaur

