Differences

This shows you the differences between the selected revisions of the page.

scripting 2015-12-16 scripting 2024-02-29 (current)
Line 10: Line 10:
&screenshotpict(scripting) &screenshotpict(scripting)
-===== Using Scripting =====+===== [[using_scripting]] Using Scripting =====
Enter the console/scripting mode by using ''[[executables|winscp.com]]''; or ''/console'' command-line parameter with ''[[executables|winscp.exe]]''. For details see [[commandline#scripting|console/scripting command-line parameters]]. Enter the console/scripting mode by using ''[[executables|winscp.com]]''; or ''/console'' command-line parameter with ''[[executables|winscp.exe]]''. For details see [[commandline#scripting|console/scripting command-line parameters]].
For automation, commands can be read from a script file specified by ''/script'' switch, passed from the command-line using the ''/command'' switch, or read from standard input of ''winscp.com''. For automation, commands can be read from a script file specified by ''/script'' switch, passed from the command-line using the ''/command'' switch, or read from standard input of ''winscp.com''.
-The script file must use UTF-8 encoding and must start with %%UTF-8%% BOM.+The script file must use UTF-8 or UTF-16 (with BOM) encoding.
-When running commands specified using ''/script'' or ''/command'', batch mode is used implicitly and overwrite confirmations are turned off. In an interactive scripting mode, the user is prompted in the same way as in GUI mode. To force batch mode (all prompts are automatically answered negatively) use the command ''[[scriptcommand_option|option batch abort]]''. For batch mode it is recommended to turn off confirmations using ''[[scriptcommand_option|option confirm off]]'' to allow overwrites (otherwise the [[ui_overwrite|overwrite confirmation prompt]] would be answered negatively, making overwrites impossible).+When running commands specified using ''/script'' or ''/command'', batch mode is used implicitly and overwrite confirmations are turned off. In an interactive scripting mode, the user is prompted in the same way as in GUI mode. To force batch mode (all prompts are automatically answered negatively) use the command ''[[scriptcommand_option#batch|option batch abort]]''. For batch mode it is recommended to turn off confirmations using ''[[scriptcommand_option#confirm|option confirm off]]'' to allow overwrites (otherwise the [[ui_overwrite|overwrite confirmation prompt]] would be answered negatively, making overwrites impossible).
Multiple sessions can be opened simultaneously. Use the ''[[scriptcommand_session|session]]'' command to switch between them. Multiple sessions can be opened simultaneously. Use the ''[[scriptcommand_session|session]]'' command to switch between them.
Line 26: Line 26:
~~AD~~ ~~AD~~
-===== Checking Results =====+===== [[result]] Checking Results =====
WinSCP [[executables]] return exit code 1 when any command is interrupted due to an error or any prompt is answered //Abort// (even automatically in batch mode). Otherwise it returns the exit code 0. WinSCP [[executables]] return exit code 1 when any command is interrupted due to an error or any prompt is answered //Abort// (even automatically in batch mode). Otherwise it returns the exit code 0.
To further analyze results of scripted operations, you will find [[logging_xml|XML logging]] useful. To further analyze results of scripted operations, you will find [[logging_xml|XML logging]] useful.
 +
 +//For more details, refer to [[faq_script_result|*]]//
Line 45: Line 47:
</code> </code>
-Note that when you are specifying commands on [[commandline|command-line]] using ''/command'', you need to surround each command by double-quote and [[commandline#syntax|escape the in-command double-quotes by doubling them]].+Note that when you are specifying commands on [[commandline#scripting|command-line]] using ''/command'', you need to surround each command by double-quote and [[commandline#syntax|escape the in-command double-quotes by doubling them]].
-To debug the quoting, enable session logging on level //Debug 1// (''/loglevel=1''). The log will show how WinSCP understands both your command-line and individual scripting commands.+To debug the quoting, enable session logging on level //Debug 1// (''[[commandline#logging|/loglevel=1]]''). The log will show how WinSCP understands both your command-line and individual scripting commands.
==== [[variables]] Environment Variables ==== ==== [[variables]] Environment Variables ====
-You can use environment variables in the commands, with syntax ''%NAME%''·((Generally do surround reference by double-quotes to cope properly with spaces in its value.)):+You can use environment variables in the commands, with syntax ''%NAME%'':((Generally do surround reference by double-quotes to cope properly with spaces in its value.))
<code winscp> <code winscp>
put "%FILE_TO_UPLOAD%" put "%FILE_TO_UPLOAD%"
Line 59: Line 61:
Note that variable expansion is different than in Windows batch files: Note that variable expansion is different than in Windows batch files:
-  * You cannot use any [[http://en.wikibooks.org/wiki/Windows_Batch_Scripting#String_processing|string processing syntax]]. +  * You cannot use any [[https://en.wikibooks.org/wiki/Windows_Batch_Scripting#String_processing|string processing syntax]]. 
-  * You cannot use [[https://en.wikipedia.org/wiki/Environment_variable#Windows_2|dynamic/pseudo environment variables]], such as ''%DATE%'' or ''%RANDOM%''.+  * You cannot use [[wp&gt;Environment_variable#Windows_2|dynamic/pseudo environment variables]], such as ''%DATE%'' or ''%RANDOM%''.
  * References to undefined variables are kept intact (not removed).   * References to undefined variables are kept intact (not removed).
  * You can use ''%WINSCP_PATH%'' to refer to WinSCP [[executable]] path.   * You can use ''%WINSCP_PATH%'' to refer to WinSCP [[executable]] path.
-==== Timestamp ====+==== [[timestamp]] Timestamp ====
-WinSCP automatically resolves ''%TIMESTAMP%'' to a real time with format ''20141024161712''.((Unless the ''%TIMESTAMP%'' variable is already set in an environment, when WinSCP is started.))+WinSCP automatically resolves ''%TIMESTAMP[rel]#format%'' to a real time (optionally to a past or future time) with the given format. The ''format'' may include ''yyyy'' for year, ''mm'' for month, ''dd'' for day, ''hh'' for hour, ''nn'' for minute and ''ss'' for second. For example, the ''%TIMESTAMP#yyyy-mm-dd%'' resolves to ''2016-06-22'' on 22 June 2016. See [[https://docwiki.embarcadero.com/Libraries/en/System.SysUtils.FormatDateTime|other formats you can use]].
-You can customize the format using syntax ''%TIMESTAMP#format%'' where ''format'' may include ''yyyy'' for year, ''mm'' for month, ''dd'' for day, ''hh'' for hour, ''nn'' for minute and ''ss'' for second. For example ''%TIMESTAMP#yyyy-mm-dd%'' resolves to ''2014-10-24''.((Syntax ''%TIMESTAMP#format%'' is resolved by WinSCP to a real time, even if ''%TIMESTAMP%'' variable is already set in environment, when WinSCP is started.)) See [[http://docwiki.embarcadero.com/Libraries/XE6/en/System.SysUtils.FormatDateTime|other formats you can use]].+The optional ''rel'' part, with syntax ''[-+]time[YDHNS]'', produces past (''-'') or future (''+'') timestamps. One of the following units must be used: ''Y'' (years), ''D'' (days), ''H'' (hours), ''N'' (minutes) or ''S'' (seconds). For example, the ''%TIMESTAMP-1D#yyyy-mm-dd%'' (the ''-1D'' meaning one day in the past) resolves to ''2016-06-21'' on 22 June 2016.
-To use ''%TIMESTAMP%'' on command-line in a batch file, you need to escape the ''%'' by doubling it to ''<nowiki>%%TIMESTAMP%%</nowiki>'', to avoid batch file interpreter trying to resolve the variable.+To use ''<nowiki>%TIMESTAMP...%</nowiki>'' on a command-line in a batch file, you need to escape the ''%'' by doubling it to ''<nowiki>%%TIMESTAMP...%%</nowiki>'', to avoid a batch file interpreter trying to resolve the variable.
==== [[arguments]] Script Arguments ==== ==== [[arguments]] Script Arguments ====
-You can reference script arguments (passed on command-line using parameter ''[[commandline#scripting|/parameter]]'') using syntax ''%N%'', where ''N'' is ordinal number of argument·((Generally do surround reference by double-quotes to cope properly with spaces in its value.)):+You can reference script arguments (passed on command-line using parameter ''[[commandline#scripting|/parameter]]'') using syntax ''%N%'', where ''N'' is ordinal number of argument:((Generally do surround reference by double-quotes to cope properly with spaces in its value.))
<code winscp> <code winscp>
put "%1%" put "%1%"
Line 81: Line 83:
==== Case Sensitivity of File Names ==== ==== Case Sensitivity of File Names ====
-Note that WinSCP treats filenames in case sensitive manner. So even if your server treats filenames in case insensitive manner, make sure you specify case properly((This is important particularly for FTP sessions.)).+Note that WinSCP treats filenames in case sensitive manner. So even if your server treats filenames in case insensitive manner, make sure you specify case properly.((This is important particularly for FTP sessions.))
-==== Comments ====+==== [[comments]] Comments ====
To insert comments into the script file, start the line with ''#'' (hash): To insert comments into the script file, start the line with ''#'' (hash):
Line 91: Line 93:
</code> </code>
-===== Commands =====+===== [[commands]] Commands =====
The following commands are implemented. The following commands are implemented.
Line 102: Line 104:
| [[scriptcommand_chmod|chmod]]  | Changes permissions of remote file | | [[scriptcommand_chmod|chmod]]  | Changes permissions of remote file |
| [[scriptcommand_close|close]]  | Closes session | | [[scriptcommand_close|close]]  | Closes session |
 +| [[scriptcommand_cp|cp]]        | Duplicates remote file |
| [[scriptcommand_echo|echo]]    | Prints message onto script output | | [[scriptcommand_echo|echo]]    | Prints message onto script output |
| [[scriptcommand_exit|exit]]    | Closes all sessions and terminates the program | | [[scriptcommand_exit|exit]]    | Closes all sessions and terminates the program |
Line 128: Line 131:
===== [[hostkey]] Verifying the Host Key or Certificate in Script ===== ===== [[hostkey]] Verifying the Host Key or Certificate in Script =====
-The first connection to an SSH server requires [[ssh_verifying_the_host_key|verification of the host key]]. To automate the verification in script, use ''-hostkey'' switch of ''[[scriptcommand_open|open]]'' command to accept the expected host key automatically.+The first connection to an SSH server requires [[ssh_verifying_the_host_key|verification of the host key]]. To automate the verification in script, use ''[[scriptcommand_open#hostkey|-hostkey]]'' switch of ''[[scriptcommand_open|open]]'' command to accept the expected host key automatically.
-You can find the key fingerprint on [[ui_fsinfo|Server and Protocol Information Dialog]]. You can also copy the key fingerprint to clipboard from the confirmation prompt on the first (interactive) connection using //Copy Key// button. //Learn more about [[faq_hostkey|obtaining host key fingerprint]]//.+You can find the key fingerprint on [[ui_fsinfo|Server and Protocol Information Dialog]]. You can also copy the key fingerprint to clipboard from the [[ssh_verifying_the_host_key|confirmation prompt]] on the first (interactive) connection using //Copy key fingerprints to clipboard// command (in the script, use SHA-256 fingerprint of the host key only). //Learn more about [[faq_hostkey|obtaining host key fingerprint]]//.
-FTPS/WebDAVS [[tls#certificate|TLS/SSL certificate]] signed by untrusted authority may also need to be verified. To automate the verification in script, use ''-certificate'' switch of ''[[scriptcommand_open|open]]'' command to accept the expected certificate automatically.+FTPS/WebDAVS [[tls#certificate|TLS/SSL certificate]] signed by untrusted authority may also need to be verified. To automate the verification in script, use ''[[scriptcommand_open#certificate|-certificate]]'' switch of ''[[scriptcommand_open|open]]'' command to accept the expected certificate automatically.
===== [[different_account]] Running a Script under a Different Account (e.g., Using a Scheduler) ===== ===== [[different_account]] Running a Script under a Different Account (e.g., Using a Scheduler) =====
-If you are going to run the script under a different account (for example using the Windows scheduler), don't forget that WinSCP still needs to access its configuration. Note that when using registry as [[config|configuration storage]], the settings are accessible only for your Windows account, so in such a case you may need to either transfer the configuration from your account registry to the other account's registry or use the [[config|INI file]] instead. +If you are going to run the script under a different account (for example [[guide_schedule|using the Windows Task Scheduler]]), make sure the script does not rely on a configuration settings that might differ on the other account. When using registry as [[config|configuration storage]], the settings are accessible only for your Windows account. Ideally, make sure the script does not rely on any external configuration, to make it completely portable. Note that the configuration also includes [[#hostkey|verified SSH host keys]] and FTPS/WebDAVS [[tls#certificate|TLS/SSL certificates]].
-Note that the configuration also includes [[#hostkey|verified SSH host keys]] and FTPS/WebDAVS [[tls#certificate|TLS/SSL certificates]]. +//For details, see the [[#configuration|next section]] and [[faq_environment|*]]//
===== [[configuration]] Sharing Configuration with Graphical Mode ===== ===== [[configuration]] Sharing Configuration with Graphical Mode =====
-WinSCP in scripting/console mode shares [[config|configuration]] with [[interfaces|graphical mode]]. This can be both advantageous and disadvantageous.+In scripting/console mode, WinSCP shares [[config|configuration]] with [[interfaces|graphical mode]] by default. While this can be useful in some cases, it can also be a disadvantage.
-The advantage is that you can use graphical interface to [[faq_script_ini|configure options for which there are no script commands]].+The disadvantage is that change to configuration in graphical mode may break your script (common example is enabling //[[ui_synchronize|Existing files only]]// option for [[task_synchronize_full|synchronization]]). Also the script is not portable to other machines, when it relies on an external configuration.
-The disadvantage is that change to configuration in graphical mode may break your script (common example is enabling //[[ui_synchronize|Existing files only]]// option for [[task_synchronize_full|synchronization]]).+If you want to protect your script from such inadvertent change or if you want to make the script portable, you should isolate its configuration from graphical mode explicitly.
-If you want to protect your script from such inadvertent change, you should isolate its configuration from graphical mode explicitly.+The best way to do that is to configure all the options you need using script commands only (''[[scriptcommand_option|option]]'' command, switches of other commands, [[session_url|session URL]]), or if no such command is available, using [[rawsettings|raw site settings]] and [[rawconfig|raw configuration]]. Finally force scripting mode to [[config#no|start with the default configuration]] using ''[[commandline#configuration|/ini=nul]]'' command-line parameter.
-The best way to do that is to configure all the options you need using script commands only (''[[scriptcommand_option|option]]'' command, switches of other commands, [[session_url|session URL]]), or if no such command is available, using [[rawsettings|raw site settings]] and [[rawconfig|raw configuration]]. Finally force scripting mode to start with the default configuration using ''/ini=nul'' [[commandline|command-line parameter]].+Alternatively [[config#export|export your configuration]] to a separate INI file and reference it using ''[[commandline#configuration|/ini=]]'' command-line parameter. Also consider setting the INI file read-only, to prevent WinSCP writing to it, when exiting. Particularly, if you are running multiple scripts in parallel, to prevent different instances of WinSCP trying to write it at the same time.
-Alternatively [[config#export|export your configuration]] to a separate INI file and reference it using ''/ini='' command-line parameter. Also consider setting the INI file read-only, to prevent WinSCP writing to it, when exiting. Particularly, if you are running multiple scripts in parallel, to prevent different instances of WinSCP trying to write it at the same time.+===== Generating Script =====
-===== Example =====+You can have WinSCP [[ui_generateurl|generate a script template for you]]. 
 + 
 +===== [[example]] Example =====
In the example below, WinSCP connects to ''example.com'' server with account ''user'', downloads file and closes the session. Then it connects to the same server with the account ''user2'' and uploads the file back. In the example below, WinSCP connects to ''example.com'' server with account ''user'', downloads file and closes the session. Then it connects to the same server with the account ''user2'' and uploads the file back.
<code winscp> <code winscp>
-# Automatically abort script on errors 
-option batch abort 
-# Disable overwrite confirmations that conflict with the previous 
-option confirm off 
# Connect # Connect
-open sftp://user:password@example.com/ -hostkey="ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"+open sftp://user:password@example.com/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx..."
# Change remote directory # Change remote directory
cd /home/user cd /home/user
-# Force binary mode transfer 
-option transfer binary 
# Download file to the local directory d:\ # Download file to the local directory d:\
get examplefile.txt d:\ get examplefile.txt d:\
Line 184: Line 183:
Save the script to the file ''example.txt''. To execute the script file use the following command. Save the script to the file ''example.txt''. To execute the script file use the following command.
<code batch> <code batch>
-winscp.com /script=example.txt+winscp.com /ini=nul /script=example.txt
</code> </code>
For simple scripts you can specify all the commands on [[commandline|command-line]] using ''/command'' switch: For simple scripts you can specify all the commands on [[commandline|command-line]] using ''/command'' switch:
<code batch> <code batch>
-winscp.com /command &quot;option batch abort" "open sftp://user:password@example.com/ -hostkey=""ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx""" "get examplefile.txt d:\" "exit"+winscp.com /ini=nul /command "open sftp://user:password@example.com/ -hostkey=""ssh-rsa 2048 xxxxxxxxxxx...""" "get examplefile.txt d:\" "exit"
</code> </code>
Line 195: Line 194:
<code batch> <code batch>
-winscp.com /command ^ +winscp.com /ini=nul /command
-····"option batch abort"+    "open sftp://user:password@example.com/ -hostkey=""ssh-rsa 2048 xxxxxxxxxxx...""" ^
-    "open sftp://user:password@example.com/ -hostkey=""ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx""" ^+
    "get examplefile.txt d:\" ^     "get examplefile.txt d:\" ^
    "exit"     "exit"
</code> </code>
 +
 +//See other [[scripts|useful example scripts]]//.
===== Converting Script to Code Based on .NET Assembly ===== ===== Converting Script to Code Based on .NET Assembly =====
Line 207: Line 207:
===== Further Reading ===== ===== Further Reading =====
  * [[guide_automation|Guide to scripting]];   * [[guide_automation|Guide to scripting]];
-  * [[faq#scripting_automation|FAQs about scripting]];+  * [[faq#scripting|FAQs about scripting]];
  * [[scripts|Useful example scripts]];   * [[scripts|Useful example scripts]];
  * [[library|WinSCP .NET assembly]].   * [[library|WinSCP .NET assembly]].

Last modified: by martin