0

I would like to use a bat script to do the task of uploading a file.

sftp -i C:\Users\Sage\.ssh\tencent root@xxx.xxx.xxx.xxx
put E:\React\sage-react\dist /home/freedom/local/dist

But when sftp is opened, the latter commands don't work.

What should I do?

1 Answers1

1

Lines in a .bat file do not simulate keyboard input. This is similar to how scripts in Linux/Unix work, where a shell interpreting the script and the terminal (terminal emulator) it uses are separate things (programs).

cmd.exe that interprets your .bat file displays a window, so it kinda acts like a terminal emulator. Still it does not feed this "terminal" the input from the .bat file as if you have typed it. It interprets and executes what's in the file.

In your case, when cmd.exe executes sftp …, it waits for it to exit before moving on to the next command in the file. This sftp does not read from the .bat file at all, it awaits interactive input, i.e. something you type.

If you want to run sftp non-interactively, you need to tell it what to do. At least with sftp from OpenSSH you can use -b to point it to its own batch file.

-b batchfile
Batch mode reads a series of commands from an input batchfile instead of stdin.

Check if your sftp supports this or similar functionality.

If your sftp supports -b then you can move this put … line from your .bat file to a different file, say C:\Users\Sage\sftp_batch1; then in your .bat file you should run sftp like this:

sftp -b C:\Users\Sage\sftp_batch1 …

This will make sftp read and execute what's in the file.


Side note: for non-interactive use consider scp. Modern scp from OpenSSH uses the SFTP protocol by default (see "History, SCP and SFTP" in this answer of mine) and the syntax scp source destination should in theory allow you to specify everything in the .bat file (no extra file needed). The command will be like:

scp -i C:\Users\Sage\.ssh\tencent E:\React\sage-react\dist root@xxx.xxx.xxx.xxx:/home/freedom/local/dist

Various implementations of scp may have their quirks, additionally we're operating where the worlds of Windows and Unix "collide" (\ vs /, interpretation of : in these paths), so it may be you need to slightly adjust the above command.