fbpx

Comandos Linux – Comando sftp

Comando Linux sftp

comando sftp

Em sistemas operacionais do tipo Unix, sftp é a interface da linha de comandos para usar o protocolo de transferência segura de arquivos SFTP . É uma versão criptografada do FTP . Ele transfere arquivos com segurança por uma conexão de rede.

Descrição

Você já deve estar familiarizado com o FTP: é um método muito simples e muito inseguro para carregar ou baixar arquivos em uma conexão de rede. Ele não fornece nenhum tipo de criptografia segura na sessão ou na transferência de dados.

O sftp fornece essa funcionalidade. Pense nisso como uma versão criptografada do ftp .

NotaSe você precisar transferir arquivos por FTP anônimo , o sftp não é o programa a ser usado. Como todas as conexões sftp são criptografadas, elas exigem um nome de usuário e senha (ou autenticação de chave pública). Portanto, para transferências FTP anônimas, use ftp regular .

Sintaxe

O sftp executa todas as operações em uma sessão ssh criptografada . Ele usa muitos dos recursos do ssh , como autenticação de chave pública e compactação de dados .

Existem quatro maneiras básicas de usar o sftp , e a sintaxe de comando para cada uma está listada aqui. (Para mais informações sobre cada opção e seus possíveis valores, consulte a seção Opções abaixo).

  1. A primeira é uma sessão interativa . Nesse modo, o sftp se conecta e faz logon no host especificado e entra no modo de comando interativo, onde você digita todos os seus comandos em um prompt. Para iniciar uma sessão interativa do sftp , use a seguinte sintaxe:
    sftp [-1246Cpqrv] [-B buffer_size ] [-b batchfile ] [-c cipher ]
         [-D sftp_server_path ] [-F ssh_config ] [-i identity_file ]
         [-l limit ] [-o ssh_option ] [-P port ] [-R num_requests ]
         [-S programa ] [-s subsistema | host sftp_server ]
    

    Consulte Modo interativo para obter um exemplo de uso do sftp dessa maneira.

  2. Você também pode usar o sftp para recuperar arquivos automaticamente, sem nenhuma interação solicitada:
    sftp [ usuário @] host [: arquivo ...]
    

    Consulte Modo de recuperação automática para obter um exemplo do uso do sftp dessa maneira.

  3. Ou você pode dizer ao sftp para iniciar sua sessão interativa em um diretório remoto específico :
    sftp [ usuário @] host [: dir [/]]
    

    Consulte Iniciando o modo interativo em um diretório remoto específico para obter um exemplo de uso do sftp dessa maneira.

  4. Por fim, você pode executar uma sessão completamente automatizada usando a opção -b . O “b” significa “modo de lote”.Para usar o modo em lote, é necessário configurar a autenticação não interativa, como autenticação de chave pública, para que você não precise digitar uma senha manualmente . A sintaxe sftp para este modo é:
    sftp -b batchfile [ utilizador @] de host
    

    Para exemplos de uso do modo em lote e um guia para configurar a autenticação de chave pública, consulte Modo em Lote .

Opções

Aqui está uma descrição de cada uma das opções listadas nas sintaxes de comando listadas acima.

-1Especifique o uso da versão 1 do protocolo , que remonta a 1997. Esta opção fornece compatibilidade com servidores muito antigos. Se você não tiver certeza de que precisa, não especifique esta opção.
-2Especifique o uso da versão 2 do protocolo, que remonta a 1997. Esta opção fornece compatibilidade com servidores muito antigos. Se você não tiver certeza de que precisa, não especifique esta opção.
-4Força o sftp a usar apenas endereços IPv4 .
-6Força o sftp a usar apenas endereços IPv6 .
-B buffer_sizeEspecifique o tamanho do buffer que o sftp usa ao transferir arquivos. Buffers maiores requerem menos viagens de ida e volta, mas requerem mais memória para fazê-lo. O padrão é 32768 bytes .
-b batchfileO modo de lote lê uma série de comandos de um arquivo em lotes de entrada em vez de stdin . Como não possui interação com o usuário, deve ser usado em conjunto com autenticação não interativa. Se batchfile for especificado como um traço (”  “), a entrada padrão será lida para o lote de comandos. O sftp será interrompido se algum dos seguintes comandos falhar: get , put , rename , ln , rm , mkdir , chdir , ls , lchdir , chmod , chown , chgrp ,lpwd , df , link simbólico e lmkdir . A finalização com erro pode ser suprimida em um comando por base de comando, prefixando o comando com um caractere ”  ” (por exemplo, -rm / tmp / file * ).
-CAtiva a compactação (via sinalizador ssh ‘s -C ).
cifra -cSeleciona a cifra a ser usada para criptografar as transferências de dados. Esta opção é passada diretamente para o ssh .
-D sftp_server_pathConecte-se diretamente a um servidor sftp local (em vez de via ssh ). Esta opção pode ser útil na depuração do cliente e servidor.
-F ssh_configEspecifica um arquivo de configuração alternativo por usuário para ssh . Esta opção é passada diretamente para o ssh .
-i identity_fileSeleciona o arquivo do qual a identidade (chave privada) para autenticação de chave pública é lida. Esta opção é passada diretamente para o ssh .
-l limiteLimita a largura de banda usada , especificada em Kbit / s.
-o ssh_optionPode ser usado para passar opções ao ssh no formato usado no ssh_config . Isso é útil para especificar opções para as quais não há sinalizador de linha de comando sftp separado . Por exemplo, para especificar uma porta alternativa, use: sftp -oPort = 24 .

EndereçoFamíliaEspecifica qual família de endereços usar ao se conectar. Os argumentos válidos são ” qualquer “, ” inet ” (use apenas IPv4) ou ” inet6 ” (use apenas IPv6).
BatchModeSe definido como ” yes “, a consulta de senha / senha será desativada. Além disso, a opção ServerAliveInterval será definida como 300 segundos por padrão. Essa opção é útil em scripts e outros trabalhos em lotes em que nenhum usuário está presente para fornecer a senha e onde é desejável detectar rapidamente uma rede interrompida. O argumento deve ser ” sim ” ou ” não “. O padrão é ” não “.
BindAddressUse o endereço especificado na máquina local como o endereço de origem da conexão. Útil apenas em sistemas com mais de um endereço. Observe que esta opção não funciona se UsePrivilegedPort estiver definido como ” yes “.
ChallengeResponseAuthenticationSpecifies whether to use “challenge-response” authentication. The argument to this keyword must be “yes” or “no“. The default is “yes“.
CheckHostIPIf this flag is set to “yes“, ssh will additionally check the host IP address in the known_hosts file. This allows ssh to detect if a host key changed due to DNS spoofing. If the option is set to “no“, the check will not be executed. The default is “yes“.
CipherSpecifies the cipher to use for encrypting the session in protocol version 1. Currently, “blowfish“, “3des“, and “des” are supported. des is only supported in the ssh client for interoperability with legacy protocol 1 implementations that do not support the 3des cipher. Its use is strongly discouraged due to cryptographic weaknesses. The default is “3des“.
CiphersSpecifies the ciphers allowed for protocol version 2 in order of preference. Multiple ciphers must be comma-separated. The supported ciphers are “3des-cbc“, “aes128-cbc“, “aes192-cbc“, “aes256-cbc“, “aes128-ctr“, “aes192-ctr“, “aes256-ctr“, “arcfour128“, “arcfour256“, “arcfour“, “blowfish-cbc“, and “cast128-cbc“.

The default value is the following really long string:

aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour

CompressãoEspecifica se deve usar compactação. O argumento deve ser ” sim ” ou ” não “. O padrão é ” não “.
CompressionLevelEspecifica o nível de compactação a ser usado se a compactação estiver ativada. O argumento deve ser um número inteiro de 1 (rápido) a 9 (mais lento, mas com melhor taxa de compactação). O nível padrão é 6 , o que é bom para a maioria dos aplicativos. O significado dos valores é o mesmo que em gzip . Observe que esta opção se aplica apenas ao protocolo versão 1.
ConnectionAttemptsEspecifica o número de tentativas (uma por segundo) a serem feitas antes de sair. O argumento deve ser um número inteiro . Isso pode ser útil em scripts se a conexão às vezes falhar. O padrão é 1 .
ConnectTimeoutEspecifica o tempo limite (em segundos) usado ao conectar-se ao servidor SSH, em vez de usar o tempo limite TCP do sistema padrão. Esse valor é usado apenas quando o destino está inoperante ou realmente inacessível, não quando ele recusa a conexão.
ControlMasterPermite o compartilhamento de várias sessões em uma única conexão de rede. Quando definido como ” yes “, o ssh escutará as conexões em um soquete de controle especificado usando o argumento ControlPath . Sessões adicionais podem se conectar a esse soquete usando o mesmo ControlPath com o ControlMaster definido como ” não ” (o padrão). Essas sessões tentarão reutilizar a conexão de rede da instância principal em vez de iniciar novas, mas voltarão a se conectar normalmente se o soquete de controle não existir ou não estiver escutando.

Definir isso como ” ask ” fará com que o ssh escute as conexões de controle,SSH_ASKPASS antes de serem aceitos. Se o ControlPath não puder ser aberto, o ssh continuará sem se conectar a uma instância principal.

O encaminhamento X11 e ssh-agent é suportado nessas conexões multiplexadas , no entanto, o monitor e o agente encaminhados pertencem à conexão principal, ou seja, não é possível encaminhar vários monitores ou agentes.

Duas opções adicionais permitem a multiplexação oportunista: tente usar uma conexão mestre, mas volte a criar uma nova, se uma já não existir. Essas opções são: ” auto ” e ” autoask “. Este último requer confirmação como o ” ask“opção.

ControlPathEspecifique o caminho para o soquete de controle usado para o compartilhamento de conexão, conforme descrito na seção ControlMaster acima, ou a cadeia ” none ” para desativar o compartilhamento de conexão. No caminho, ‘ % L ‘ será substituído pelo primeiro componente do nome do host local , ‘ % l ‘ será substituído pelo nome do host local (incluindo qualquer nome de domínio), ‘ % h ‘ será substituído pelo nome do host de destino, ‘ % n ‘ será substituído pelo nome do host de destino original especificado na linha de comando, ‘ % p ‘ a porta, ‘ % r ‘ pelo nome de usuário de logon remoto e ‘ % u ‘. É recomendável que qualquer ControlPath usado para compartilhamento de conexão oportunista inclua pelo menos % h , % p e % r . Isso garante que as conexões compartilhadas sejam identificadas exclusivamente.
ControlPersistQuando usada em conjunto com o ControlMaster , especifica que a conexão mestre deve permanecer aberta em segundo plano (aguardando futuras conexões do cliente) após o fechamento da conexão inicial do cliente. Se definido como ” não “, a conexão principal não será colocada em segundo plano e será fechada assim que a conexão inicial do cliente for fechada. Se definido como ” yes “, a conexão principal permanecerá em segundo plano indefinidamente (até ser interrompida ou fechada por um mecanismo como a opção ssh ” -O exit “). Se definido como um tempo em segundos ou um tempo em qualquer um dos formatos documentados em sshd_config, a conexão principal em segundo plano será encerrada automaticamente depois de permanecer inativa (sem conexões do cliente) pelo tempo especificado.
GlobalKnownHostsFileEspecifica um ou mais arquivos para usar no banco de dados de chaves do host global, separados por espaços em branco. O padrão é / etc / ssh / ssh_known_hosts , / etc / ssh / ssh_known_hosts2 .
GSSAPIAuthenticationEspecifica se a autenticação do usuário com base no GSSAPI (Interface de Programa de Aplicativo de Serviço de Segurança Genérica) é permitida. O padrão é ” não “. Observe que esta opção se aplica apenas ao protocolo versão 2.
GSSAPIDelegateCredentialsForward (delegate) credentials to the server. The default is “no“. Note that this option applies to protocol version 2 connections using GSSAPI.
HashKnownHostsIndicates that ssh should hash hostnames and addresses when they are added to ~/.ssh/known_hosts. These hashed names may be used normally by ssh and sshd, but they do not reveal identifying information should the file’s contents be disclosed. The default is “no“. Note that existing names and addresses in known hosts files will not be converted automatically, but may be manually hashed using the ssh-keygen key generator.

Use of this option may break facilities such as tab-completion that rely on being able to read unhashed hostnames from ~/.ssh/known_hosts.

HostRestricts the following declarations (up to the next Host keyword) to be only for those hosts that match one of the patterns given after the keyword. If more than one pattern is provided, they should be separated by whitespace. A single “*” as a pattern can be used to provide global defaults for all hosts. The host is the hostname argument given on the command line (i.e. the name is not converted to a canonicalized hostname before matching).

A pattern entry may be negated by prefixing it with an exclamation mark (“!“). If a negated entry is matched, then the Host entry is ignored, regardless of whether any other patterns on the line match. Negated matches are therefore useful to provide exceptions for wildcard matches.

HostbasedAuthenticationSpecifies whether to try rhosts-based authentication with public key authentication. The argument must be “yes” or “no“. The default is “no“. This option applies to protocol version 2 only and is similar to RhostsRSAAuthentication.
HostKeyAlgorithmsSpecifies the protocol version 2 host key algorithms that the client wants to use in order of preference. The default for this option is the following really, really long string:

[email protected][email protected][email protected][email protected],[email protected][email protected],[email protected], ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521, ssh-rsa,ssh-dss

If hostkeys are known for the destination host then this default is modified to prefer their algorithms.

HostKeyAliasSpecifies an alias that should be used instead of the real hostname when looking up or saving the host key in the host key database files. This option is useful for tunneling SSH connections or for multiple servers running on a single host.
HostNameSpecifies the real hostname to log into. This can be used to specify nicknames or abbreviations for hosts. If the hostname contains the character sequence ‘%h‘, then this will be replaced with the hostname specified on the command line (this is useful for manipulating unqualified names). The default is the name given on the command line. Numeric IP addresses are also permitted (both on the command line and in HostName specifications).
IdentityFileSpecifies a file from which the user’s DSA, ECDSA or DSA authentication identity is read. The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_dsa~/.ssh/id_ecdsa and ~/.ssh/id_rsa for protocol version 2. Additionally, any identities represented by the authentication agent will be used for authentication. ssh(1) will try to load certificate information from the file name obtained by appending -cert.pub to the path of a specified IdentityFile.

The file name may use the tilde syntax to refer to a user’s home directory or one of the following escape characters: ‘%d‘ (local user’s home directory), ‘%u‘ (local user name), ‘%l‘ (local hostname), ‘%h‘ (remote hostname) or ‘%r‘ (remote username).

It is possible to have multiple identity files specified in configuration files; all these identities will be tried in sequence. Multiple IdentityFile directives will add to the list of identities tried (this behaviour differs from that of other configuration directives).

IdentitiesOnlySpecifies that ssh should only use the authentication identity files configured in the ssh_config files, even if ssh-agent offers more identities. The argument to this keyword must be “yes” or “no“. This option is intended for situations where ssh-agent offers many different identities. The default is “no“.
IPQoSSpecifies the IPv4 type-of-service or DSCP class for connections. Accepted values are “af11“, “af12“, “af13“, “af21“, “af22“, “af23“, “af31“, “af32“, “af33“, “af41“, “af42“, “af43“, “cs0“, “cs1“, “cs2“, “cs3“, “cs4“, “cs5“, “cs6“, “cs7“, “ef“, “lowdelay“, “throughput“, “reliability“, or a numeric value. This option may take one or two arguments, separated by whitespace. If one argument is specified, it is used as the packet class unconditionally. If two values are specified, the first is automatically selected for interactive sessions and the second for non-interactive sessions. The default is “lowdelay” for interactive sessions and “throughput” for non-interactive sessions.
KbdInteractiveAuthenticationSpecifies whether to use keyboard-interactive authentication. The argument to this keyword must be “yes” or “no“. The default is “yes“.
KbdInteractiveDevicesSpecifies the list of methods to use in keyboard-interactive authentication. Multiple method names must be comma-separated. The default is to use the server specified list. The methods available vary depending on what the server supports. For an OpenSSH server, it may be zero or more of: “bsdauth“, “pam“, and “skey“.
KexAlgorithmsSpecifies the available KEX (Key Exchange) algorithms. Multiple algorithms must be comma-separated. The default is the following very long string:

ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521, diffie-hellman-group-exchange-sha256, diffie-hellman-group-exchange-sha1, diffie-hellman-group14-sha1, diffie-hellman-group1-sha1

LogLevelGives the verbosity level that is used when logging messages from ssh. The possible values are: QUIETFATALERRORINFOVERBOSEDEBUGDEBUG1DEBUG2, and DEBUG3. The default is INFODEBUG and DEBUG1 are equivalent. DEBUG2 and DEBUG3 each specify higher levels of verbose output.
MACsSpecifies the MAC (message authentication code) algorithms in order of preference. The MAC algorithm is used in protocol version 2 for data integrity protection. Multiple algorithms must be comma-separated. The default is the following string:

hmac-md5,hmac-sha1,[email protected], hmac-ripemd160,hmac-sha1-96,hmac-md5-96, hmac-sha2-256,hmac-sha2-256-96,hmac-sha2-512, hmac-sha2-512-96

NoHostAuthenticationForLocalhostThis option can be used if the home directory is shared across machines. In this case localhost will refer to a different machine on each of the machines and the user will get many warnings about changed host keys. However, this option disables host authentication for localhost. The argument to this keyword must be “yes” or “no“. The default is to check the host key for localhost.
NumberOfPasswordPromptsSpecifies the number of password prompts before giving up. The argument to this keyword must be an integer. The default is 3.
PasswordAuthenticationSpecifies whether to use password authentication. The argument to this keyword must be “yes” or “no“. The default is “yes“.
PKCS11ProviderSpecifies which PKCS#11 (Public Key Cryptography Standard number 11) provider to use. The argument to this keyword is the PKCS#11 shared library ssh should use to communicate with a PKCS#11 token providing the user’s private RSA key.
PortSpecifies the port number to connect on the remote host. The default is 22.
PreferredAuthenticationsSpecifies the order in which the client should try protocol 2 authentication methods. This allows a client to prefer one method (e.g., keyboard-interactive) over another method (e.g., password). The default is:

gssapi-with-mic,hostbased,publickey, keyboard-interactive,password

ProtocolSpecifies the protocol versions ssh should support in order of preference. The possible values are ‘1‘ and ‘2‘. Multiple versions must be comma-separated. When this option is set to “2,1” ssh will try version 2 and fall back to version 1 if version 2 is not available. The default is ‘2‘.
ProxyCommandSpecifies the command to use to connect to the server. The command string extends to the end of the line, and is executed with the user’s shell. In the command string, any occurrence of ‘%h‘ will be substituted by the hostname to connect, ‘%p‘ by the port, and ‘%r‘ by the remote username. The command can be basically anything, and should read from its standard input and write to its standard output. It should eventually connect an sshd server running on some machine, or execute sshd -i somewhere. Host key management will be done using the HostName of the host being connected (defaulting to the name typed by the user). Setting the command to “none” disables this option entirely. Note that CheckHostIP is not available for connects with a proxy command.

This directive is useful in conjunction with nc and its proxy support. For example, the following directive would connect via an HTTP proxy at 192.0.2.0:

ProxyCommand /usr/bin/nc -X connect -x 192.0.2.0:8080 %h %p

PubkeyAuthenticationSpecifies whether to try public key authentication. The argument to this keyword must be “yes” or “no“. The default is “yes“. This option applies to protocol version 2 only.
RekeyLimitSpecifies the maximum amount of data that may be transmitted before the session key is renegotiated. The argument is the number of bytes, with an optional suffix of ‘K‘, ‘M‘, or ‘G‘ to indicate Kilobytes, Megabytes, or Gigabytes, respectively. The default is between ‘1G‘ and ‘4G‘, depending on the cipher. This option applies to protocol version 2 only.
RhostsRSAAuthenticationSpecifies whether to try rhosts based authentication with RSA host authentication. The argument must be “yes” or “no“. The default is “no“. This option applies to protocol version 1 only and requires ssh to be setuid root.
RSAAuthenticationSpecifies whether to try RSA authentication. The argument to this keyword must be “yes” or “no“. RSA authentication will only be attempted if the identity file exists, or an authentication agent is running. The default is “yes“. Note that this option applies to protocol version 1 only.
SendEnvSpecifies what variables from the local environment should be sent to the server. Note that environment passing is only supported for protocol 2. The server must also support it, and the server must be configured to accept these environment variables. Variables are specified by name, which may contain wildcard characters. Multiple environment variables may be separated by whitespace or spread across multiple SendEnv directives. The default is not to send any environment variables.
ServerAliveIntervalSets a timeout interval in seconds after which if no data has been received from the server, ssh will send a message through the encrypted channel to request a response from the server. The default is 0, indicating that these messages will not be sent to the server, or 300 if the BatchMode option is set. This option applies to protocol version 2 only. ProtocolKeepAlives and SetupTimeOut are Debian-specific compatibility aliases for this option.
ServerAliveCountMaxSets the number of server alive messages (see below) which may be sent without ssh receiving any messages back from the server. If this threshold is reached while server alive messages are being sent, ssh will disconnect from the server, terminating the session. It is important to note that the use of server alive messages is very different from TCPKeepAlive. The server alive messages are sent through the encrypted channel and therefore will not be spoofable. The TCP keepalive option enabled by TCPKeepAlive is spoofable. The server alive mechanism is valuable when the client or server depend on knowing when a connection has become inactive.

The default value is 3. If, for example, ServerAliveInterval (see below) is set to 15 and ServerAliveCountMax is left at the default, if the server becomes unresponsive, ssh will disconnect after approximately 45 seconds. This option applies to protocol version 2 only; in protocol version 1 there is no mechanism to request a response from the server to the server alive messages, so disconnection is the responsibility of the TCP stack.

StrictHostKeyCheckingIf this flag is set to “yes“, ssh will never automatically add host keys to the ~/.ssh/known_hosts file, and refuses to connect to hosts whose host key has changed. This provides maximum protection against trojan horse attacks, though it can be annoying when the /etc/ssh/ssh_known_hosts file is poorly maintained or when connections to new hosts are frequently made. This option forces the user to manually add all new hosts. If this flag is set to “no“, ssh will automatically add new host keys to the user known hosts files. If this flag is set to “ask“, new host keys will be added to the user known host files only after the user has confirmed that is what they really want to do, and ssh will refuse to connect to hosts whose host key has changed. The host keys of known hosts will be verified automatically in all cases. The argument must be “yes“, “no“, or “ask“. The default is “ask“.
TCPKeepAliveSpecifies whether the system should send TCP keepalive messages to the other side. If they are sent, death of the connection or crash of one of the machines will be properly noticed. This option only uses TCP keepalives (as opposed to using ssh-level keepalives), so takes a long time to notice when the connection dies. As such, you probably want the ServerAliveInterval option as well. However, this means that connections will die if the route is down temporarily, and some people find it annoying.

The default is “yes” (to send TCP keepalive messages), and the client will notice if the network goes down or the remote host dies. This is important in scripts, and many users want it too.

To disable TCP keepalive messages, the value should be set to “no“.

UsePrivilegedPortSpecifies whether to use a privileged port for outgoing connections. The argument must be “yes” or “no“. The default is “no“. If set to “yes“, ssh must be setuid root. Note that this option must be set to “yes” for RhostsRSAAuthentication with older servers.
UserSpecifies the user to use for log in. This can be useful when a different username is used on different machines. This saves the trouble of having to remember to give the username on the command line.
UserKnownHostsFileSpecifies one or more files to use for the user host key database, separated by whitespace. The default is ~/.ssh/known_hosts~/.ssh/known_hosts2.
VerifyHostKeyDNSSpecifies whether to verify the remote key using DNS and SSHFP resource records. If this option is set to “yes“, the client will implicitly trust keys that match a secure fingerprint from DNS. Insecure fingerprints will be handled as if this option was set to “ask“. If this option is set to “ask“, information on fingerprint match will be displayed, but the user will still need to confirm new host keys according to the StrictHostKeyChecking option. The argument must be “yes“, “no“, or “ask“. The default is “no“. Note that this option applies to protocol version 2 only.
-P portSpecifies the port to connect to on the remote host.
-pPreserves modification times, access times, and modes from the original files transferred.
-qQuiet mode: disables the progress meter as well as warning and diagnostic messages from ssh.
-R num_requestsSpecify how many requests may be outstanding at any one time. Increasing this may slightly improve file transfer speed but will increase memory usage. The default is 64 outstanding requests.
-rRecursively copy entire directories when uploading and downloading. Note that sftp does not follow symbolic links encountered in the tree traversal.
-S programName of the program to use for the encrypted connection. The program must understand ssh options.
-s subsystem | sftp_serverSpecifies the SSH2 subsystem or the path for an sftp server on the remote host. A path is useful for using sftp over protocol version 1, or when the remote sshd does not have an sftp subsystem configured.
-vRaise logging level. This option is also passed to ssh.

Interactive mode

In interactive mode, sftp logs you into the remote system and places you at a prompt that is similar to the command prompt on your local system. It offers you a limited, but very useful, set of commands with which you can navigate the remote file system and send and receive files.

Let’s say you want to start an interactive sftp session on the server named “server.myhost.com“. And, let’s say your user account on server.myhost.com is named “user“. From your system’s command line, You can start the session using the command:

sftp [email protected]

Or, if your username on your local system is also “user“, you could type:

sftp server.myhost.com

…and your username “user” will automatically be sent as the username.

The server will respond by asking you for your password:

[email protected]'s password:

…and if you enter it correctly, you will receive a “you’re connected” message, and the sftp prompt, like this:

Connected to server.myhost.com.
sftp>

You can now move around in the filesystem with “cd directory“, list files with “ls“, download files with “get filename“, and upload files with “put filename“. It’s pretty much identical to an interactive ftp session, except it’s encrypted and secure.

When you’re done, you can log off with the “bye” command (“exit” also works), and sftp will exit.

Here’s a list of the commands you can use in Interactive Mode:

Interactive mode commands

byeClose the session and quit sftp. Same as “exit“.
cd pathChange the remote working directory to path.
chgrp grp pathChange group of file path to grp.

path may contain wildcard characters and may match multiple files. grp must be a numeric GID (group ID).

chmod mode pathChange the permissions of file path to mode.

path may contain wildcard characters and can match multiple files.

chown own pathChange owner of file path to own.

path may contain wildcard characters and may match multiple files.

own must be a numeric UID (user ID).

df [-hi] [path]Display usage information for the filesystem holding the current directory (or path if specified). If the -h flag is specified, the capacity information will be displayed using “human-readable” suffixes. The -i flag requests display of inode information in addition to capacity information. This command is only supported on servers that implement the “[email protected]” extension.
exitClose the session and quit sftp. Same as “bye“.
get [-Pprremote-path [local-path]Retrieve the remote-path and store it on the local machine. If the local path name is not specified, it is given the same name it has on the remote machine.

remote-path may contain wildcard characters and may matcal-path is specified, then local-path must specify a directory.

If either the -P or -p flag is specified, then full file permissions and access times are copied too.

If the -r flag is specified then directories will be copied recursively. Note that sftp does not follow symbolic links when performing recursive transfers.

helpDisplay a help message.
lcd pathChange the local working directory to path.
lls [ls-options [path]]Display a directory listing of the local directory path, or the local working directory if path is not specified.

ls-options may contain any flags supported by the local system’s ls command.

path may contain wildcard characters and may match multiple files.

lmkdir pathCreate a directory on your local system specified by path.
ln [-soldpath newpathCreate a link from oldpath to newpath. If the -s flag is specified the created link is a symbolic link, otherwise it is a hard link.
lpwdPrint the name of the local working directory.
ls [-1afhlnrSt] [path]Display a remote directory listing of either path or the current directory if path is not specified. path may contain wildcard characters and can match multiple files.

The following flags alter the behaviour of ls:

-1Display the listing in a single column.
-aList files whose names begin with a dot (“.“), which otherwise would not be listed.
-fDo not sort the list. The default sort order is lexicographical.
-hWhen used in conjunction with -l or -n options (which create a long-format list), this option specifies “human-readable” unit suffixes for file sizes. For instance, instead of “4096” bytes, this option will list the size as “4.0K“.
-lCreate a “long-format” list, displaying additional file details including permissions and ownership information.
-nCria uma lista de formato longo, como a opção -l , mas com informações de usuário e grupo apresentadas numericamente.
-rInverta a ordem de classificação da listagem.
-SClassifique a listagem por tamanho de arquivo, do maior para o menor.
-tClassifique a listagem pela hora da última modificação, da mais recente para a mais antiga.
lumask umaskDefina umask local como umask .
caminho mkdirCrie um diretório no sistema remoto especificado pelo caminho .
progressoAlterna a exibição de um medidor de progresso.
coloque [ -Ppr ] caminho local [ caminho remoto ]Carregue o caminho local e armazene-o na máquina remota. Se o nome do caminho remoto não for especificado, ele receberá o mesmo nome que possui na máquina local.

O caminho local pode conter caracteres curinga e corresponder a vários arquivos. Se isso ocorrer, e o caminho remoto for especificado, o caminho remoto deverá especificar um diretório.

Se o sinalizador -P ou -p for especificado, as permissões de arquivo completas e os tempos de acesso também serão copiados.

Se o sinalizador -r for especificado, os diretórios serão copiados recursivamente. Observe que o sftp não segue os links simbólicos ao executar transferências recursivas.

pwdExibe o nome do diretório ativo remoto.
SairSaia do sftp .
renomear caminho antigo caminho novoRenomeie um arquivo remoto de caminho antigo para caminho novo .
caminho rmExclua o arquivo remoto especificado pelo caminho .
caminho rmdirRemova o diretório remoto especificado pelo caminho .
symlink oldpath newpathCrie um link simbólico para o caminho antigo chamado newpath .
versãoExibe a versão do protocolo sftp .
comandoExecute o comando command em um shell local .
!Solte em uma concha local. Digite exit para retornar à sessão sftp .
?O mesmo que ” ajuda “.

Notas:

  • Os comandos do Modo Interativo não diferenciam maiúsculas de minúsculas, portanto, não importa se você os escreve com letras maiúsculas ou minúsculas (ou uma mistura de ambos). Os nomes de arquivos ainda diferenciam maiúsculas de minúsculas.
  • Qualquer nome de arquivo ou diretório que contenha espaços deve ser colocado entre aspas ou o servidor os interpretará como nomes separados.

Modo de recuperação automática

Nesse modo, você pode especificar o nome do caminho exato do arquivo (ou arquivos) que deseja recuperar no próprio comando sftp . Por exemplo, se você deseja obter o arquivo de documentos / portfolio.zip do servidor remoto files.myhost.com (onde seu nome de usuário é myname ), você poderia usar o comando:

sftp [email protected] : documents / portfolio.zip

Quando você executa esse comando, o sftp se conecta a files.myhost.com , solicita sua senha e, uma vez autenticado, ele tenta fazer o download do arquivo documents / portfolio.zip . Como não colocamos uma barra no início do nome do diretório, ele procurará documentos em seu diretório pessoal no servidor. Se encontrar portfolio.zip , fará o download.

A saída terá a seguinte aparência:

Buscando /home/myname/documents/portfolio.zip no portfolio.zip

… e o sftp sairá. Você também pode especificar um local para o arquivo a ser baixado. Por exemplo, este comando:

sftp [email protected] : documents / portfolio.zip / tmp

… fará o download do portfolio.zip no diretório / tmp . Ou você pode especificar um nome completamente diferente para o arquivo baixado:

sftp [email protected] : documents / portfolio.zip /tmp/portfolio-new.zip

… e a saída indicará o novo nome do arquivo:

Buscando /home/myname/documents/portfolio.zip /tmp/porfolio-new.zip

Você também pode especificar caracteres curinga no nome do arquivo, por exemplo:

sftp [email protected] : documentos / *. zip

… e o sftp fará o download de todos os arquivos com a extensão .zip no diretório remoto de documentos . A saída listará cada arquivo em sua própria linha, assim:

Buscando /home/myname/documents/portfolio.zip no portfolio.zip
Fetching /home/myname/documents/resume.zip to resume.zip
Fetching /home/myname/documents/profile-pic.zip to profile-pic.zip

Starting interactive mode in a specific remote directory

Sometimes it’s more convenient to start an interactive mode session right from a specific remote directory. You can do this by specifying it on the command line:

sftp [email protected]:documents/budget/april/
[email protected]'s password: 
Connected to files.myhost.com.
Changing to: /home/myname/documents/budget/april/
sftp>

Batch mode

It’s also possible to run sftp in a completely scripted fashion. This is called batch mode, and it allows you to perform sftp transfers without any interaction at the keyboard. This is useful, for instance, if you want to set up a recurring transfer in a cron job, or a one-time scheduled transfer using the at command.

However, because batch mode is completely non-interactive, it does not allow you to enter a username and password when connecting to the server. So, to use batch mode, you’ll have to log in automatically. The standard way to do this, and the most secure, is to use public key authentication. Let’s go over that quickly.

Setting Up Public Key Authentication

Public Key Authentication allows you to log into a remote server securely without typing in your password. First, you generate two keys on your local system: a private key and a public key. Then you copy the text of your public key onto the remote server. After that, as long as you have the private key on your local machine, you can log into the remote machine without typing in a password.

To do this, the first step is to generate the public and private keys.

The keys will be located in the directory .ssh in your home directory on your local system. First, check to see if the .ssh directory already exists:

ls -d ~/.ssh

This will either return the directory name:

/home/username/.ssh

…or tell you that it doesn’t exist:

ls: cannot access /home/username/.ssh: No such file or directory

If it doesn’t exist, we need to create it before the next step:

mkdir ~/.ssh

Next, we need to make sure this directory has the correct permissions. You want to ensure that you’re the only person who can access this directory (read, write, and execute). For a directory, the octal value of this file mode is 700. Let’s change the permissions on our .ssh directory:

chmod 700 ~/.ssh

Now we need to generate the keys themselves. The program used to generate key pairs for the ssh protocol is called ssh-keygen. Run it at the command line without any options:

ssh-keygen

It will prompt you for the information it needs to generate the keys. Use all the default values (press Enter at every prompt).

NoteOne of the prompts will ask you for a passphrase, which offers an additional level of security on top of the encrypted private key. Here we will leave the password blank. If you want to use a password with your key, you should use a program called ssh-agent to load your key into memory; this will allow you to use a password-protected key without having to type in the password more than once.

The output from ssh-keygen will look something like this:

Generating public/private rsa key pair.
Enter file in which to save the key (/home/username/.ssh/id_rsa): 
Created directory '/home/username/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/username/.ssh/id_rsa.
Your public key has been saved in /home/username/.ssh/id_rsa.pub.
The key fingerprint is:
d4:7b:66:c4:e6:ba:78:87:e7:23:08:c7:0d:d7:b0:7f username@crunch
The key's randomart image is:
+--[ RSA 2048]----+
|                 |
|         ...     |
|        . .P+    |
|       .. o=.    |
|     ...S+.e=    |
|      . o .=. E  |
|       o ... .   |
|      ..e.+.+    |
|        ...=..   |
+-----------------+

You’ll even get a neat piece of art representing your public key, which you can print out and hang on your wall, if you like.

Your keys are now generated. There are two files, id_rsa and id_rsa.pub. We need to change the permissions on these files as well, so that no one but you can access them (read, write, and execute). The octal value of these permission bits is 700.

chmod 700 ~/.ssh/id_rsa*

And make sure the directory has the same permission bits set:

chmod 700 ~/.ssh

Now ssh to your server. Let’s say it’s called myhost.com:

ssh [email protected]

Enter your password and log in. Once you’re at your server’s command prompt, check to see if the .ssh directory exists there. On the server:

ls -d ~/.ssh

If it doesn’t exist, create it, and give it the appropriate permissions, just like on your local system. On the server:

mkdir ~/.ssh
chmod 700 ~/.ssh

Same for the authorized_keys file. First check that it exists. On the server:

ls ~/.ssh/authorized_keys

If it doesn’t, create it. You can use touch to create an empty file. On the server:

touch ~/.ssh/authorized_keys
chmod 700 ~/.ssh/authorized_keys

Of course, if the directory and file exist already, you don’t need to create them. Either way, once you know the ~/.ssh/authorized_keys file exists, you can log out of the server:

logout

Which will return you to your local system command prompt.

Now you need to place the contents of your local public key file (~/.ssh/id_rsa.pub, which you created earlier with ssh-keygen) into the file ~/.ssh/authorized_keys on your server.

The contents of this file are all in one very long line (no line breaks). You can look at it yourself with the cat command:

cat ~/.ssh/id_rsa.pub

…and it will look something like this:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDTiP0LXi74qgpp6VBqzro67QOGtum10
t2epYsOm6kKncf62JVMSlwYH7QwAskxkA6ripvo+TlwRBqqLaF2ACX4CivQkoabqsdFAd
uGcKVICUFZaexUmw2eIEKF4qCOvRDP/Juol1S+ID1glYJRSqDcmAb3jApTRDMXM/w7Tl3
qz5/cp3MINKM3+apBfe7F7iDezjQ/U0HqtH2+Np83u4X2G+LIFnpV0RdalkqCuM6tSv2C
m4FdPazsIwSmFptBKnw00IdIqYpnkQmOJMk47cGDzqczii7KMCy3wRNqkaLwefRB0MZeJ
ipz4+a27kQEqerAIHt37/MMT5XNqn3mqbI myuser@myhostname

This line of text needs to be placed into the authorized_keys file on your server, on its own line. There are several ways to do this: you could copy the text on your local server, open the file using a text editor on the server, and paste it in on its own line. Or, you could use a program called ssh-copy-id, which is part of the default ssh installation on many systems. However, here we will append it directly to the file using ssh itself.

If your remote username is myusername and your server name is myhost.com, you would run this command:

cat ~/.ssh/id_rsa.pub | ssh [email protected] 'cat >> ~/.ssh/authorized_keys'

This runs the cat command on your public key file, pipes the output to ssh, which takes that input and appends it directly to the authorized_keys file on the remote machine.

Now your public key is installed on the server, and you should be able to log in without a password, as well as conduct batch sftp sessions.

NoteIf the server is still asking you for your password when you try to log in, check that the server’s ssh daemon configuration, located by default in /etc/ssh/sshd_config, contains the following two lines:

RSAAuthentication yes
PubkeyAuthentication yes

These are part of the default configuration, so you shouldn’t need to add them, set them, or un-comment them in the configuration file. However, they are required for public key authentication. If it’s not working, this is the first place you should check.

Executing the batch sftp session

To run a batch sftp session, create a text file containing the sequence of sftp commands to be run on the server, with each command on its own line. For instance, if you want to automate the uploading of a set of files called image01.jpgimage02.jpg… into a directory on the remote server called images in your home directory, you could create a text file called mybatch.txt which contains the following commands:

cd images
put image*.jpg

Then, you would execute the batch with the following command:

sftp -b mybatch.txt [email protected]

…and sftp will output the results of the commands, for example:

sftp> cd images
sftp> put image*.jpg
Uploading image01.jpg to /home/myname/images/image01.jpg
Uploading image02.jpg to /home/myname/images/image02.jpg
Uploading image03.jpg to /home/myname/images/image03.jpg

After all commands have been executed (successfully or not), sftp will log out and return you to the command line.

Examples

sftp myhost.com

This command attempts to initiate an interactive sftp session with the server myhost.com. The name used to log in will be the same as the username with which you ran the command. Once you are successfully logged in, you will see a message similar to the following, along with the sftp> command prompt:

Remote system type is UNIX. 
Using ASCII mode to transfer files. 
sftp>
sftp [email protected]

Same as the above command, but attempts to log in with the username fred.

sftp [email protected]:/home/fred/images

Attempts to initiate an interactive sftp session with the server myhost.com, using the name fred to log in. Upon successful login, you will begin the session in the directory /home/fred/images.

sftp [email protected]:/home/fred/images/picture.jpg

Attempts to download the file /home/fred/images/picture.jpg from the server myhost.com using the username fred to log in. If the file exists, it will be downloaded to the local working directory, and then sftp will exit.

sftp -b batch.txt [email protected]

Attempts to execute the sftp commands in the text file batch.txt, on the server myhost.com, as the user named fred. The commands in the file batch.txt must be listed one per line. For the session to be initiated, the server and local client must be configured so that no keyboard input is required to log in; see Setting Up Public Key Authentication above for more information.

Interactive command examples

The following examples may be run from the sftp> prompt once an interactive session has been initiated. See Interactive Mode Commands above for a complete list of interactive commands and options.

pwd

Prints the name of the remote working directory.

lpwd

Prints the name of the local working directory.

ls

List the contents of the remote working directory.

lls

List the contents of the local working directory.

cd documents

Changes the remote working directory to the subdirectory documents.

lcd documents

Changes the local working directory to the subdirectory documents.

get mydocs.zip

Download the remote file mydocs.zip into the local working directory.

get mydocs.zip /home/fred

Download the remote file mydocs.zip into the local directory /home/fred. If the directory /home/fred does not exist, sftp will attempt to download the file into the local directory /home and name it fred.

Notesftp does not recognize the tilde shortcut for home directories (“~“), so you have to use the complete name of a home directory if you’re specifying it in sftp.

get mydocs.zip /home/fred/downloaded-docs.zip

Faça o download do arquivo remoto mydocs.zip no diretório local / home / fred , fornecendo o novo nome de download-docs.zip após o download.

documentos mkdir

Crie os documentos do diretório no diretório ativo remoto.

colocar documents.zip

Carregue o arquivo local documents.zip no diretório de trabalho remoto.

coloque /home/fred/documents/documents.zip /home/fred/documents/mydoc.zip

Faça o upload do arquivo local /home/fred/documents/documents.zip no diretório remoto / home / fred / documents , renomeando-o para mydoc.zip após o upload.

coloque /home/fred/images/image*.jpg / home / fred / images

Faça o upload de todos os arquivos no diretório local / home / fred / images cujo nome comece com image e termine com o sufixo .jpg no diretório remoto / home / fred / images .

renomeie /home/fred/file.txt /home/fred/newfile.txt

Renomeie o arquivo remoto /home/fred/file.txt , fornecendo o nome newfile.txt .

rm /home/fred/newfile.txt

Exclua o arquivo remoto /home/fred/newfile.txt .

! commandname opção1 opção2

Execute o comando commandname option1 option2 em seu sistema local sem desconectar da sessão sftp .

tchau

Desconecte da sessão sftp e saia do sftp .

ftp – Conduza uma sessão FTP interativa em uma conexão de rede segura.
slogin – Faça login em um sistema remoto com segurança.

21 de novembro de 2019

Sobre nós

A Linux Force Brasil é uma empresa que ama a arte de ensinar. Nossa missão é criar talentos para a área de tecnologia e atender com excelência nossos clientes.

CNPJ: 13.299.207/0001-50
SAC:         0800 721 7901

[email protected]

Comercial  Comercial: (11) 3796-5900

Suporte:    (11) 3796-5900
[email protected]

Copyright © Linux Force Security  - Desde 2011.