WinSCP can log session events to a log file.
Events can be logged in two formats:
- Session log: Events are logged in unstructured form with configurable level of verbosity. Information logged differ with protocol used. This format is useful to troubleshoot problems with connection. You should also include this log when reporting bugs or asking for support.
- XML log: Events are logged in structured form in XML format. This format includes less information than session log. However its format is documented and independent from protocol used. You will find this format particularly useful to analyze automatically performed operations, such as when using scripting.
Advertisement
Note that passwords and passphrases are not stored to either log format.
Logging can be enabled from Logging page of Preferences dialog. Logging can also be enabled from command-line using /log
and /xmllog
parameters respectively, what is particularly useful with scripting. In .NET assembly, session logging is enabled using Session.SessionLogPath
.1
The Logging page on the Preferences dialog allows user to configure session and XML logging.
Advertisement
Refer to documentation of page sections:
- Session log
- XML log
- Further Reading
Session log
To enable logging to a file, check Enable session logging on level.
To increase a verbosity of the session log, select Debug 1 or Debug 2 level. You will probably need these (together with a logging to file), when reporting bugs only. The Debug 2 level can significantly deteriorate performace. To decrease a verbosity of the session log, select Reduced level.
Specify local path to log file into Log path box. Log file name can contain following patterns: !Y
(year), !M
(month), !D
(day), !T
(time), !@
(hostname), !S
(session name), !P
(process ID), !!
(exclamation mark).
If you select Append option, and the logging file already exists, session log will be appended to the end of the file. Otherwise the existing file will be overwritten.
You can limit a log file size by specifying a maximum size in bytes in Rotate log files after reaching box. Supported units are K
, M
and G
. If a log file reaches the configured limit, it is archived to a file with extension .1
, .2
, etc. You can limit number of archived log files using Delete old logs files, keep … files checkbox.
If you enable logging to file in mid-session the past events will not be written to the log retrospectively. Note that to log several sessions simultaneously to file, you need to ensure unique names of the log files (e.g. using some of the patterns above). Passwords are not written to log file.
Tick Log passwords and other sensitive information to turn off obfuscation of passwords and other sensitive information in session log. It is useful when debugging authentication issues.
Advertisement
XML log
To enable XML log, check Enable XML logging to file and specify local path to log file. You can use the same patterns as for session log file (see above).
It is not possible to change XML log file name in middle of the session.
Further Reading
Read more about Preferences dialog and its other pages.
XML logging is one of the WinSCP log formats. An XML log includes structured records describing operations done by WinSCP over session. The log format is protocol independent.
In many cases you do not have to deal with the XML log file directly. WinSCP .NET assembly can do it for you.
Advertisement
- Purpose
- Using
- Representing Operations in Log
- Representing Results/Errors
- Results/Errors of Operations
- Results/Errors of Script
- Grouping Operations for Commands
- Elements
- call
- checksum
- chmod
- cp
- download
- ls
- mkdir
- mv
- rm
- stat
- upload
- touch
- Schema
- Example
- Interpreting/Parsing
- General
- Transforming XML Log to Text Output Using XSLT Transformation
Advertisement
Purpose
Primary purpose of the XML logging is to provide machine-readable description of automatically performed operations, such as when using scripting.
The XML logging is useful e.g. to:
- Find a list of files that were actually uploaded/downloaded, when transferring a whole directory or when transferring files matching a mask;
- Get a directory listing;
- Record operations done during synchronization.
Note that while the XML logging can be used also for GUI sessions, it does not record background transfers.
Using
The XML logging, being used along with scripting, is most typically enabled from command-line, using /xmllog
parameter. It can be enabled in preferences too.
An overall format of the XML log file follows:
<?xml version="1.0" encoding="UTF-8"?> <session xmlns="http://winscp.net/schema/session/1.0" name="martin@example.com" start="2009-03-02T19:34:57.734Z"> <!-- operations --> </session>
The top level session
tag represents one logical session, which may consist of several physical sessions, particularly when connection is lost. Attribute name
refers to name of the logical session. Attribute start
indicates time when the session was initiated.1
The session
element includes child elements, where each element represents single log entry, i.e. single physical operation with remote file over the logical session.
Representing Operations in Log
Every entry in the XML log represents single physical operation over the session. Typically this would be an operation with remote file.
Single logical operation (in scripting or GUI) may actually involve multiple physical operations, each represented with separate log element. For example upload of file (e.g. using put
scripting command) may be represented by up to three elements, upload
for actual upload, touch
for preserving timestamp and chmod
for preserving permissions.
Note that some logical operations does not have corresponding log element (e.g. creation of symbolic link). Such operations are omitted from the XML log.
Representing Results/Errors
Results/Errors of Operations
Result of a specific operation is represented by child result
element of respective operation element. The result
element has boolean success
attribute.
Advertisement
<result success="true" />
If success
is false
, result
element will typically include one or more message
elements with error message(s). The error message is free text, that may be language-, protocol- or even server-specific. So you should not try to process it automatically.
The following example is from English version, connected with SFTP protocol to OpenSSH server:
<result success="false"> <message>Cannot open remote file '/home/user/examplefile.txt'.</message> <message>No such file or directory. Error code: 2 Error message from server: No such file Request code: 3</message> </result>
With some protocols, each of the physical operations are performed individually. With some protocols, set of operations may be performed in atomic form. This may prevent mapping error to specific operation. In this case the error may be associated with more operations, resulting in its duplication in the XML log.
Some errors may not be associated with any operation in the XML log. This particularly happens when:
- An error is actually not associated with particular physical operation. Example is invalid script command syntax.
- The particular operation that failed does not have corresponding log element.
Results/Errors of Script
When the script fails (WinSCP exit code is 1), the top level session
element or group
element (when grouping is enabled) will include one or more failure
elements, each containing one or more message
elements with error message(s).
If the particular error was associated with a physical operation, the error message will be included both in result
child element of the respective operation element and in failure
child element of top level session
element or group
element.
<upload> <filename value="d:examplefile.txt" /> <result success="false"> <message>Cannot create remote file '/home/user/examplefile.txt'.</message> <message>Permission denied. Error code: 3 Error message from server: Permission denied Request code: 3</message> </result> </upload> <failure> <message>Cannot create remote file '/home/user/examplefile.txt'.</message> <message>Permission denied. Error code: 3 Error message from server: Permission denied Request code: 3</message> </failure>
Advertisement
Grouping Operations for Commands
When using the XML logging together with scripting, operations and failures belonging to the same command can be grouped using parent group
element:
<group name="put -preservetime d:*.txt" start="2021-12-03T14:25:10.204Z"> <upload> <filename value="d:readme.txt" /> <destination value="/home/user/readme.txt" /> <size value="15345" /> <result success="true" /> </upload> <upload> <filename value="d:examplefile.txt" /> <result success="false"> <message>Cannot create remote file '/home/user/examplefile.txt'.</message> <message>Permission denied. Error code: 3 Error message from server: Permission denied Request code: 3</message> </result> </upload> <failure> <message>Cannot create remote file '/home/user/examplefile.txt'.</message> <message>Permission denied. Error code: 3 Error message from server: Permission denied Request code: 3</message> </failure> </group>
Grouping can be enabled on command-line.
Grouping is particularly useful, when you are continuously reading the XML log file. By receiving </group>
you know that the command execution has finished.
Elements
All operation elements below have result
child element in addition to listed child elements.
The result
child element is always present. Many other child elements may be absent in case of error.
call
Execution of arbitrary remote shell command (with SFTP and SCP protocols) or execution of a protocol command (with FTP protocol).
Elements:
Element | Description |
---|---|
command |
Command (in value attribute) |
destination |
Absolute path to current remote working directory (in value attribute) |
output |
Command standard output (in value attribute) |
erroroutput |
Command error output (in value attribute) |
Advertisement
Example:
<call> <command value="ps" /> <destination value="/home/user" /> <output value=" PID TTY TIME CMD 16969 ? 00:00:00 sshd 16970 ? 00:00:00 sftp-server 32647 ? 00:00:00 bash 1466 ? 00:00:00 ps" /> <result success="true" /> </call>
Associated script commands: call
checksum
Calculating a checksum of a remote file.
Elements:
Element | Description |
---|---|
filename |
Absolute path to a remote file (in value attribute) |
algorithm |
Name of a checksum algorithm used (in value attribute) |
checksum |
Hex dump of a calculated checksum (in value attribute) |
Example:
<checksum> <filename value="/home/martin/public_html/index.html" /> <algorithm value="sha-1" /> <checksum value="bb4dfa9b51d3f6c99b5ec6c12ebf9cade79f43c4" /> <result success="true" /> </checksum>
Associated script commands: checksum
chmod
Changing of permissions of one (or more) remote file.
Elements:
Element | Description |
---|---|
filename |
Absolute path to remote file (in value attribute) |
permissions |
Permissions in Unix format rwxrwxrwx (in value attribute) |
Advertisement
With SCP protocol optional boolean attribute recursive
indicates, if permissions were changed recursively with single operation.
Example:
<chmod recursive="true"> <filename value="/home/martin/public_html/about.html" /> <permissions value="rwxr-xr-x" /> <result success="true" /> </chmod>
Associated script commands: chmod
, keepuptodate -permissions
, put -permissions
, synchronize remote|both -permissions
cp
Duplication of one remote file or directory.
Elements:
Element | Description |
---|---|
filename |
Absolute path to source local file (in value attribute) |
destination |
Absolute path to destination remote file (in value attribute) |
Example:
<cp> <filename value="/home/martin/public_html/about.html" /> <destination value="/home/martin/backup/about.html.20171220" /> <result success="true" /> </cp>
Associated script commands: cp
download
Downloading of single file.
Elements:
Element | Description |
---|---|
filename |
Absolute path to source remote file (in value attribute) |
destination |
Absolute path to destination local file (in value attribute)2 |
size |
Number of bytes transferred. |
Advertisement
Example:
<download> <filename value="/home/martin/public_html/about.html" /> <destination value="d:wwwabout.htm" /> <size value="55387" /> <result success="true" /> </download>
Associated script commands: get
, synchronize local|both
ls
Listing of remote directory (only when explicitly requested using ls
scripting command).
Elements:
Element | Description |
---|---|
destination |
Absolute path to remote directory (in value attribute) |
files |
Container of file elements |
Elements of file
element:
Element | Description |
---|---|
filename |
Name of file without path (in value attribute) |
type |
Type of file as in Unix ls command output, e.g. d for directory (in value attribute) |
size |
Size of file in bytes (in value attribute) |
modification |
Modification timestamp (in value attribute)1 |
permissions |
File permissions in Unix format rwxrwxrwx (in value attribute) |
owner |
File owner (in value attribute) |
group |
File group (in value attribute) |
Example:
<ls> <destination value="/home/martin/public_html" /> <files> <file> <filename value="." /> <type value="d" /> <modification value="2008-12-22T12:16:23.000Z" /> <permissions value="rwxr-xr-x" /> </file> <file> <filename value=".." /> <type value="d" /> <modification value="2008-03-25T08:15:53.000Z" /> <permissions value="rwxr-xr-x" /> </file> <file> <filename value=".htaccess" /> <type value="-" /> <size value="107" /> <modification value="2008-12-02T06:59:58.000Z" /> <permissions value="rw-r--r--" /> </file> <file> <filename value="about.html" /> <type value="-" /> <size value="24064" /> <modification value="2007-10-04T21:43:02.000Z" /> <permissions value="rw-r--r--" /> </file> </files> <result success="true" /> </ls>
Advertisement
Associated script commands: ls
mkdir
Creating of remote directory.
Elements:
Element | Description |
---|---|
filename |
Absolute path to remote directory (in value attribute) |
Example:
<mkdir> <filename value="/home/martin/public_html/images" /> <result success="true" /> </mkdir>
Associated script commands: keepuptodate
, mkdir
, put
, synchronize remote|both
mv
Moving of one remote file or directory to different remote directory or renaming of one remote file or directory.
Elements:
Element | Description |
---|---|
filename |
Absolute path to source local file (in value attribute) |
destination |
Absolute path to destination remote file (in value attribute)2 |
Example:
<mv> <filename value="/home/martin/public_html/about.html" /> <destination value="/tmp/about.bak" /> <result success="true" /> </mv>
Associated script commands: mv
rm
Deleting of one (or more) remote file or directory.
Advertisement
Elements:
Element | Description |
---|---|
filename |
Absolute path to remote file of directory (in value attribute) |
With SCP protocol optional boolean attribute recursive
indicates, if remote directory was recursively deleted with all contained files with single operation.
Example:
<rm recursive="true"> <filename value="/home/martin/public_html/images" /> <result success="true" /> </rm>
Associated script commands: get -delete
, keepuptodate -delete
, rm
, rmdir
, synchronize local|both -delete
stat
Listing of remote file attributes.
Elements:
Element | Description |
---|---|
filename |
Absolute path to remote file (in value attribute) |
file |
Container of file attributes. See specification in description of ls element. Note that file element within stat misses filename subelement, comparing to file element within ls /files . |
Example:
<stat> <filename value="/home/martin/public_html/about.html" /> <file> <type value="-" /> <size value="24064" /> <modification value="2007-10-04T21:43:02.000Z" /> <permissions value="rw-r--r--" /> </file> <result success="true" /> </stat>
Associated script commands: stat
upload
Uploading of single file.
Advertisement
Elements:
Element | Description |
---|---|
filename |
Absolute path to source local file (in value attribute) |
destination |
Absolute path to destination remote file (in value attribute)2 |
size |
Number of bytes transferred. |
Example:
<upload> <filename value="d:wwwabout.htm" /> <destination value="/home/martin/public_html/about.html" /> <size value="55387" /> <result success="true" /> </upload>
Associated script commands: keepuptodate
, put
, synchronize remote|both
touch
Changing of remote file timestamp.
Elements:
Element | Description |
---|---|
filename |
Absolute path to remote file (in value attribute) |
modification |
Modification timestamp (in value attribute)1 |
Example:
<touch> <filename value="/home/martin/public_html/about.html" /> <modification value="2008-12-28T11:22:19.000Z" /> <result success="true" /> </touch>
Associated script commands: keepuptodate
, put -preservetime
, synchronize remote|both
Schema
An XML schema for the XML log is available at:
http://winscp.net/schema/session/1.0
Advertisement
Example
Note that the group
elements will be included, if enabled only.
<?xml version="1.0" encoding="UTF-8"?> <session xmlns="http://winscp.net/schema/session/1.0" name="martin@example.com" start="2012-01-04T14:25:53.173Z"> <group name="put -preservetime -permissions=644 d:wwwabout.htm" start="2012-01-04T14:28:45.393Z"> <upload> <filename value="d:wwwabout.htm" /> <destination value="/home/martin/public_html/about.html" /> <result success="true" /> </upload> <touch> <filename value="/home/martin/public_html/about.html" /> <modification value="2008-12-28T11:22:19.000Z" /> <result success="true" /> </touch> <chmod> <filename value="/home/martin/public_html/about.html" /> <permissions value="rw-r--r--" /> <result success="true" /> </chmod> </group> <group name="rm about.bak" start="2012-01-04T14:28:47.892Z"> <rm> <filename value="/home/martin/public_html/about.bak" /> <result success="false"> <message>No such file or directory. Error code: 2 Error message from server: No such file Request code: 13</message> </result> </rm> <failure> <message>No such file or directory. Error code: 2 Error message from server: No such file Request code: 13</message> </failure> </group> </session>
Interpreting/Parsing
General
To parse the XML log, use any XML parser available.
Advertisement
If possible, using WinSCP .NET assembly is the preferred approach, which hides away the XML log file from your application.
If you want to parse the XML log yourself anyway, see following guides to learn how to do that in different development environments:
- Advanced FTP/SFTP scripting (Windows script host; Java or VB script);
- SFTP file transfers in .NET (.NET; C# or VB.NET);
- Interpreting XML log for advanced scripting (.NET, C#).
Transforming XML Log to Text Output Using XSLT Transformation
You can use XSLT transformation to convert the XML log to plain text output (or any other format).
For example to generate a plain text list of successfully downloaded files from the following XML log (log.xml
):
<?xml version="1.0" encoding="UTF-8"?> <session xmlns="http://winscp.net/schema/session/1.0" name="user@host" start="2021-12-03T06:45:57.008Z"> <download> <filename value="/path/file1.txt" /> <destination value="C:pathfile1.txt" /> <size value="2022" /> <result success="true" /> </download> <download> <filename value="/path/file2.txt" /> <destination value="C:pathfile2.txt" /> <size value="5782" /> <result success="true" /> </download> </session>
use the following XSLT (download.xslt
):
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:winscp="http://winscp.net/schema/session/1.0"> <xsl:output method="text" encoding="UTF-8"/> <xsl:strip-space elements="*"/> <xsl:template match='winscp:download[winscp:result[@success="true"]]/winscp:filename'> <xsl:value-of select="@value"/> <xsl:text> </xsl:text> </xsl:template> </xsl:stylesheet>
You can execute it using any XSLT processor:
- Microsoft
msxsl.exe
(deprecated, but available from Internet Archive):
msxsl.exe log.xml download.xslt
- Libxml2
xsltproc.exe
:
xsltproc.exe download.xslt log.xml
Advertisement
The output will be:
/path/file1.txt /path/file2.txt
For a more complex example, see Custom directory listing format (CSV).
В этой статье рассмотрим возможность логирования соединений по SFTP протоколу. Этим соединением пользуется программа WinSCP, которая позволяет работать с файлами (копировать/перемещать/изменять/удалять) в Linux из ОС Windows. Для чего это требуется. Всё дело в том, что при подключении к ОС CentOS 6.9 с использованием программы WinSCP, это не будет отражено ни в одном логе. В данной […]
В этой статье рассмотрим возможность логирования соединений
по SFTP протоколу. Этим
соединением пользуется программа WinSCP, которая позволяет работать с файлами (копировать/перемещать/изменять/удалять)
в Linux из ОС Windows.
Рассматривать логирование будем на ОС CentOS 6.9.
Для чего это требуется. Всё дело в том, что при подключении к
ОС CentOS 6.9 с
использованием программы WinSCP,
это не будет отражено ни в одном логе.
В данной статье мы сделаем так, чтобы в лог записывались
манипуляции, которые производятся через WinSCP при подключению к нашему серверу.
Настройка логирования
Итак, приступим к настройкам самого логирования.
Для начала нам необходимо несколько изменить параметры
запуска sftp-сервера.
Для этого открываем в режиме редактирования файл /etc/ssh/sshd_config и
находим следующую строку:
Subsystem sftp /usr/libexec/openssh/sftp-server
Проще всего найти её будет по ключевому слову sftp
К ней необходимо будет дописать следующие параметры: -l INFO -f AUTH. Должна получиться следующая строка:
Subsystem sftp /usr/libexec/openssh/sftp-server -l INFO -f AUTH
Здесь параметр –l отвечает за уровень логирования sftp-сервера. Существуют
следующие уровни логирования: QUIET, FATAL, ERROR,
INFO,
VERBOSE,
DEBUG,
DEBUG1,
DEBUG2
и DEBUG3.
При этом DEBUG и DEBUG1
считаются эквивалентными, а уровень DEBUG3 – наивысшим уровнем логирования. В нашем случае, для
отображения действий подключающихся пользователей, достаточно будет уровня INFO.
Подробнее о ключах и настройках smtp-сервера можно узнать, выполнив в
консоли команду:
man sftp-server
Открываем в режиме редактирования файл /etc/rsyslog.conf и
добавляем в конец файла следующую строку:
auth.* /var/log/sftp.log
В качестве второго аргумента (/var/log/sftp.log) указываем
имя файла, в который будут писаться логи sftp-соединений.
Перезапускаем службы sshd и rsyslog командами:
service sshd restart
service rsyslog restart
Тестирование
Теперь при подключении к нашему серверу с использованием программы
WinSCP, все выполненные
действия будут логироваться и доступны к просмотру в файле /var/log/sftp.log.
Рассмотрим отображение в логе некоторых основных моментов
работы.
Подключение к серверу с использованием WinSCP будет
выглядеть в логе следующим образом:
- 192.168.170.111, IP адрес в конце самой верхней строки — это адрес клиента, который подключается к серверу.
- [29070] – уникальный идентификатор сессии. С помощью этого параметра можно отследить, какие действия выполнял подключённый пользователь.
К примеру, для того, чтобы узнать, кто подключался к серверу
по sftp за сегодня (27 Ноября), достаточно в консоли ввести команду:
fgrep 'Nov 27 ' /var/log/sftp.log | grep 'session opened'
Рис. 3.
Отключение от сервера будет выглядеть в логе следующим образом:
При отключении основной сессии WinSCP также будут отключены и дополнительные (к примеру, при открытии файла для редактирования в WinSCP будет создана дополнительная сессия от того же IP адреса).
Поэтому, совершенно нормально, если при закрытии одной вкладки в WinSCP, по логам можно будет увидеть, что закрылось сразу несколько соединений.
Создание, редактирование, удаление файлов выглядит в логе
следующим образом:
На скриншоте выше, блок:
1 – Создание файла. Можно определить по характерным параметрам: наличие lstat с именем создаваемого файла и после этого идёт sent status No such file. Это означает, что файл не найден и будет создан, после чего открывается его редактирование. Также определить, что файл создаётся можно по флагу редактирования CREATE, при открытии его.
2 – редактирование файла. Можно определить по флагу READ при открытии файла. Также здесь присутствует информация о количестве считанных и записанных байт. Если файл был перезаписан, добавляется последнее время его модификации.
3 – удаление файла. Заключается всего в одной строке: remove name “/path_to_file/name_file”.
На этом статья о рассмотрении логирования SFTP-соединений завершена.
I want to logging all information when WinSCP script shows in console to log file. I try to use output redirection, but log file remains empty.
D:ProgramsWinSCPWinSCP.exe /script=sync.txt > log.txt
Also I tried to add /console
parameter, but result is the same.
P.S. Using /log
option is not very useful for me, because it write too much incomprehensible information.
asked Mar 19, 2019 at 22:03
3
winscp.exe
is a GUI application. It does not have a standard output that can be redirected.
For your purposes, there’s winscp.com
which is a console application. And so it does have a standard output that can be redirected.
D:ProgramsWinSCPWinSCP.com /script=sync.txt > log.txt
Read about WinSCP executables.
You may also be interested in using «reduced» session logging (WinSCP 5.14 and newer only):
D:ProgramsWinSCPWinSCP.com /script=sync.txt /loglevel=-1 /log=log.log
Or XML logging:
D:ProgramsWinSCPWinSCP.com /script=sync.txt /xmllog=log.xml
Both options can be used with winscp.exe
too, but for scripting, it generally makes sense to use winscp.com
.
answered Mar 26, 2019 at 7:17
Martin PrikrylMartin Prikryl
186k54 gold badges478 silver badges963 bronze badges
To enable logging to a file, check Enable session logging on level. To increase a verbosity of the session log, select Debug 1 or Debug 2 level. You will probably need these (together with a logging to file), when reporting bugs only. To decrease a verbosity of the session log, select Reduced level.
Where is the WinSCP log file?
For a start, C:writable%TEMP%tologWinSCP.
How do I check my WinSCP history?
2 Answers. You can configure how long the completed transfers display using the option Display completed transfer in queue. you can enable logging. That should give you the history of all the files you transfer.
Why is Sftp not working?
Make sure you log in to your server’s IP ADDRESS (not your domain) with the SYSTEM USER used to create your app; attempting to connect to your domain directly is one of the most common causes of SFTP connection failures. Reset your system user password in ServerPilot. Restart your SFTP client.
Which port should I use for FTP?
port 21
Why does FTP have two ports?
Ports like FTP and DHCP have two numbers because as we know the data communication can be allowed when there is a secured connection(not necessarily) between two computers ie a client and a server. So FTP has two ports. Likewise, port 21 is used for data transmission. Hence the requirement of two ports.
Does port 21 use UDP or TCP?
Well-known ports
Port | TCP | Description |
---|---|---|
20 | Yes | File Transfer Protocol (FTP) data transfer |
21 | Yes | File Transfer Protocol (FTP) control (command) |
22 | Yes | Secure Shell (SSH), secure logins, file transfers (scp, sftp) and port forwarding |
23 | Yes | Telnet protocol—unencrypted text communications |
Is Sftp always port 22?
SFTP (SSH File Transfer Protocol), not to be confused with FTPS (Secure File Transfer Protocol), runs on top of the SSH (Secure Shell) protocol and by default uses port number 22 for communications.
Is SCP UDP or TCP?
SCP is a simple protocol which lets a server and client have multiple conversations over a single TCP connection. The protocol is designed to be simple to implement, and is modelled after TCP.
Is FTPS a TCP?
> FTP over SSL Clients (FTPS) Explicit FTPS control connections take place on TCP port 21. Implicit FTPS control connections take place on TCP port 990. Once the control channel is established, the client and server negotiate a port for either PASSIVE or ACTIVE MODE data transfers.
winscp windows 10
Logging into a shared linux server
I want maximum logging (even showing password)
this is a desktop computer and I am not visiting important sites.
SSH / Telnet SoftwareWindows OSLinux
Я хочу регистрировать всю информацию, когда сценарий WinSCP отображается в консоли в файл журнала. Я пытаюсь использовать перенаправление вывода, но файл журнала остается пустым.
D:ProgramsWinSCPWinSCP.exe /script=sync.txt > log.txt
Также я попытался добавить параметр /console
, но результат тот же.
P.S. Использование опции /log
для меня не очень полезно, потому что в ней пишется слишком много непонятной информации.
1 ответ
Лучший ответ
winscp.exe
— это приложение с графическим интерфейсом . У него нет стандартного вывода, который можно было бы перенаправить.
Для ваших целей существует winscp.com
, которое является консольным приложением. И поэтому он имеет стандартный вывод, который можно перенаправить.
D:ProgramsWinSCPWinSCP.com /script=sync.txt > log.txt
Прочтите об исполняемых файлах WinSCP.
Вы также можете быть заинтересованы в использовании «сокращенного» ведения журнала сеанса (только WinSCP 5.14 и новее ):
D:ProgramsWinSCPWinSCP.com /script=sync.txt /loglevel=-1 /log=log.log
Или ведение журнала XML:
D:ProgramsWinSCPWinSCP.com /script=sync.txt /xmllog=log.xml
Оба варианта можно использовать и с winscp.exe
, но для написания сценариев обычно имеет смысл использовать winscp.com
.
1
Martin Prikryl
26 Мар 2019 в 10:17
Hi have a WinSCP script to put a file on remote server using SFTP, which is working fine. But I would enable logging to a text file on a local directory.
I have the following script
option batch on
option confirm off
# connect minute session
open sftp://xyz.com:22/ -privatekey=E:PK*.ppk
# force binary mode transfer
option transfer ascii
# navigate to mediacom and put file
lcd "E:export"
cd /mediacom/testdir
put "CI_Tst.tab"
# disconnect daily session
close
# exit WinScP
exit
Many I know how I can log results of above script to a local file?
|
|||
sanechichek
24.04.12 — 15:20 |
Подскажите, пожалуйста, по каком принципу работает логирования в WinSCP? Мне нужно автоматически проверять этот лог, было ли подключения, и скопировались ли файлы, в противном случае сообщить ошибку? Сейчас для меня ключевым словом является «Failed», но может можно сделать как то более правильно? |
||
pumbaEO
1 — 24.04.12 — 15:20 |
а, plink от putty чем тебе не нравиться? |
||
Лефмихалыч
2 — 24.04.12 — 15:22 |
я работал. не понимаю, чего ты хочешь. |
||
sanechichek
3 — 24.04.12 — 15:24 |
(1) просто с WinSCP уже разобрался, единсвенное осталось разобратся как опредилить что все выполнилось без сбоев. А чем plink от putty лучше? |
||
sanechichek
4 — 24.04.12 — 15:26 |
(2) мне нужно определить выполнились ли все опрерации или нет, может не было соединения или случайно прервалось в момент синхронизации каталогов, как мне об этом узнать? |
||
pumbaEO
5 — 24.04.12 — 15:28 |
Коммандная строка, результат работы парситься… но с winscp из коммандной строки не работал не знаю. p.s. всегда для себя держал в уме winscp — графический менеджер, plink — коммандная строка… |
||
sanechichek
6 — 24.04.12 — 15:35 |
(5)я с winscp работаю тоже через командную строку (winscp.exe /console /command «option batch abort» «open user@example.com» «get examplefile.txt d:» «exit»), а как Вы парсите результат работы? Просто я сейчас захожу в лог winscp и если нахожу слово «Failed», то сообщаю об ошибке, но мне этот вариант не сильно нравится. |
||
Лефмихалыч
7 — 24.04.12 — 15:36 |
(6) почему нельзя проверять, есть ли examplefile.txt на диске? |
||
sanechichek
8 — 24.04.12 — 15:42 |
(7) потому что, я буду копировать файлы (их очень много) с сфтп-сервера, а какие там должны быть файлы, я не знаю, мне нужно все скопировать с сервера и потом их обрабатывать и нужно избежать ошибки что 10 файлов скопировалось, потом разорвалось соединения с сервером и остальные файлы не скопировались. |
||
pumbaEO
9 — 24.04.12 — 15:46 |
Сделай перед началом копирования ls и потом сравни список файлов. |
||
sanechichek 10 — 24.04.12 — 16:00 |
(9) спасибо, буду пробывать, но наверное остановлюсь на варианте с проверкой лога на наличие «Failed». |
TurboConf — расширение возможностей Конфигуратора 1С