repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
bitprophet/ssh
demos/demo.py
agent_auth
def agent_auth(transport, username): """ Attempt to authenticate to the given transport using any of the private keys available from an SSH agent. """ agent = ssh.Agent() agent_keys = agent.get_keys() if len(agent_keys) == 0: return for key in agent_keys: print 'Trying ssh-agent key %s' % hexlify(key.get_fingerprint()), try: transport.auth_publickey(username, key) print '... success!' return except ssh.SSHException: print '... nope.'
python
def agent_auth(transport, username): """ Attempt to authenticate to the given transport using any of the private keys available from an SSH agent. """ agent = ssh.Agent() agent_keys = agent.get_keys() if len(agent_keys) == 0: return for key in agent_keys: print 'Trying ssh-agent key %s' % hexlify(key.get_fingerprint()), try: transport.auth_publickey(username, key) print '... success!' return except ssh.SSHException: print '... nope.'
[ "def", "agent_auth", "(", "transport", ",", "username", ")", ":", "agent", "=", "ssh", ".", "Agent", "(", ")", "agent_keys", "=", "agent", ".", "get_keys", "(", ")", "if", "len", "(", "agent_keys", ")", "==", "0", ":", "return", "for", "key", "in", "agent_keys", ":", "print", "'Trying ssh-agent key %s'", "%", "hexlify", "(", "key", ".", "get_fingerprint", "(", ")", ")", ",", "try", ":", "transport", ".", "auth_publickey", "(", "username", ",", "key", ")", "print", "'... success!'", "return", "except", "ssh", ".", "SSHException", ":", "print", "'... nope.'" ]
Attempt to authenticate to the given transport using any of the private keys available from an SSH agent.
[ "Attempt", "to", "authenticate", "to", "the", "given", "transport", "using", "any", "of", "the", "private", "keys", "available", "from", "an", "SSH", "agent", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/demos/demo.py#L37-L55
train
bitprophet/ssh
ssh/sftp_file.py
SFTPFile._read_prefetch
def _read_prefetch(self, size): """ read data out of the prefetch buffer, if possible. if the data isn't in the buffer, return None. otherwise, behaves like a normal read. """ # while not closed, and haven't fetched past the current position, and haven't reached EOF... while True: offset = self._data_in_prefetch_buffers(self._realpos) if offset is not None: break if self._prefetch_done or self._closed: break self.sftp._read_response() self._check_exception() if offset is None: self._prefetching = False return None prefetch = self._prefetch_data[offset] del self._prefetch_data[offset] buf_offset = self._realpos - offset if buf_offset > 0: self._prefetch_data[offset] = prefetch[:buf_offset] prefetch = prefetch[buf_offset:] if size < len(prefetch): self._prefetch_data[self._realpos + size] = prefetch[size:] prefetch = prefetch[:size] return prefetch
python
def _read_prefetch(self, size): """ read data out of the prefetch buffer, if possible. if the data isn't in the buffer, return None. otherwise, behaves like a normal read. """ # while not closed, and haven't fetched past the current position, and haven't reached EOF... while True: offset = self._data_in_prefetch_buffers(self._realpos) if offset is not None: break if self._prefetch_done or self._closed: break self.sftp._read_response() self._check_exception() if offset is None: self._prefetching = False return None prefetch = self._prefetch_data[offset] del self._prefetch_data[offset] buf_offset = self._realpos - offset if buf_offset > 0: self._prefetch_data[offset] = prefetch[:buf_offset] prefetch = prefetch[buf_offset:] if size < len(prefetch): self._prefetch_data[self._realpos + size] = prefetch[size:] prefetch = prefetch[:size] return prefetch
[ "def", "_read_prefetch", "(", "self", ",", "size", ")", ":", "# while not closed, and haven't fetched past the current position, and haven't reached EOF...", "while", "True", ":", "offset", "=", "self", ".", "_data_in_prefetch_buffers", "(", "self", ".", "_realpos", ")", "if", "offset", "is", "not", "None", ":", "break", "if", "self", ".", "_prefetch_done", "or", "self", ".", "_closed", ":", "break", "self", ".", "sftp", ".", "_read_response", "(", ")", "self", ".", "_check_exception", "(", ")", "if", "offset", "is", "None", ":", "self", ".", "_prefetching", "=", "False", "return", "None", "prefetch", "=", "self", ".", "_prefetch_data", "[", "offset", "]", "del", "self", ".", "_prefetch_data", "[", "offset", "]", "buf_offset", "=", "self", ".", "_realpos", "-", "offset", "if", "buf_offset", ">", "0", ":", "self", ".", "_prefetch_data", "[", "offset", "]", "=", "prefetch", "[", ":", "buf_offset", "]", "prefetch", "=", "prefetch", "[", "buf_offset", ":", "]", "if", "size", "<", "len", "(", "prefetch", ")", ":", "self", ".", "_prefetch_data", "[", "self", ".", "_realpos", "+", "size", "]", "=", "prefetch", "[", "size", ":", "]", "prefetch", "=", "prefetch", "[", ":", "size", "]", "return", "prefetch" ]
read data out of the prefetch buffer, if possible. if the data isn't in the buffer, return None. otherwise, behaves like a normal read.
[ "read", "data", "out", "of", "the", "prefetch", "buffer", "if", "possible", ".", "if", "the", "data", "isn", "t", "in", "the", "buffer", "return", "None", ".", "otherwise", "behaves", "like", "a", "normal", "read", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/sftp_file.py#L120-L147
train
bitprophet/ssh
ssh/sftp_file.py
SFTPFile.chmod
def chmod(self, mode): """ Change the mode (permissions) of this file. The permissions are unix-style and identical to those used by python's C{os.chmod} function. @param mode: new permissions @type mode: int """ self.sftp._log(DEBUG, 'chmod(%s, %r)' % (hexlify(self.handle), mode)) attr = SFTPAttributes() attr.st_mode = mode self.sftp._request(CMD_FSETSTAT, self.handle, attr)
python
def chmod(self, mode): """ Change the mode (permissions) of this file. The permissions are unix-style and identical to those used by python's C{os.chmod} function. @param mode: new permissions @type mode: int """ self.sftp._log(DEBUG, 'chmod(%s, %r)' % (hexlify(self.handle), mode)) attr = SFTPAttributes() attr.st_mode = mode self.sftp._request(CMD_FSETSTAT, self.handle, attr)
[ "def", "chmod", "(", "self", ",", "mode", ")", ":", "self", ".", "sftp", ".", "_log", "(", "DEBUG", ",", "'chmod(%s, %r)'", "%", "(", "hexlify", "(", "self", ".", "handle", ")", ",", "mode", ")", ")", "attr", "=", "SFTPAttributes", "(", ")", "attr", ".", "st_mode", "=", "mode", "self", ".", "sftp", ".", "_request", "(", "CMD_FSETSTAT", ",", "self", ".", "handle", ",", "attr", ")" ]
Change the mode (permissions) of this file. The permissions are unix-style and identical to those used by python's C{os.chmod} function. @param mode: new permissions @type mode: int
[ "Change", "the", "mode", "(", "permissions", ")", "of", "this", "file", ".", "The", "permissions", "are", "unix", "-", "style", "and", "identical", "to", "those", "used", "by", "python", "s", "C", "{", "os", ".", "chmod", "}", "function", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/sftp_file.py#L230-L242
train
bitprophet/ssh
ssh/sftp_file.py
SFTPFile.chown
def chown(self, uid, gid): """ Change the owner (C{uid}) and group (C{gid}) of this file. As with python's C{os.chown} function, you must pass both arguments, so if you only want to change one, use L{stat} first to retrieve the current owner and group. @param uid: new owner's uid @type uid: int @param gid: new group id @type gid: int """ self.sftp._log(DEBUG, 'chown(%s, %r, %r)' % (hexlify(self.handle), uid, gid)) attr = SFTPAttributes() attr.st_uid, attr.st_gid = uid, gid self.sftp._request(CMD_FSETSTAT, self.handle, attr)
python
def chown(self, uid, gid): """ Change the owner (C{uid}) and group (C{gid}) of this file. As with python's C{os.chown} function, you must pass both arguments, so if you only want to change one, use L{stat} first to retrieve the current owner and group. @param uid: new owner's uid @type uid: int @param gid: new group id @type gid: int """ self.sftp._log(DEBUG, 'chown(%s, %r, %r)' % (hexlify(self.handle), uid, gid)) attr = SFTPAttributes() attr.st_uid, attr.st_gid = uid, gid self.sftp._request(CMD_FSETSTAT, self.handle, attr)
[ "def", "chown", "(", "self", ",", "uid", ",", "gid", ")", ":", "self", ".", "sftp", ".", "_log", "(", "DEBUG", ",", "'chown(%s, %r, %r)'", "%", "(", "hexlify", "(", "self", ".", "handle", ")", ",", "uid", ",", "gid", ")", ")", "attr", "=", "SFTPAttributes", "(", ")", "attr", ".", "st_uid", ",", "attr", ".", "st_gid", "=", "uid", ",", "gid", "self", ".", "sftp", ".", "_request", "(", "CMD_FSETSTAT", ",", "self", ".", "handle", ",", "attr", ")" ]
Change the owner (C{uid}) and group (C{gid}) of this file. As with python's C{os.chown} function, you must pass both arguments, so if you only want to change one, use L{stat} first to retrieve the current owner and group. @param uid: new owner's uid @type uid: int @param gid: new group id @type gid: int
[ "Change", "the", "owner", "(", "C", "{", "uid", "}", ")", "and", "group", "(", "C", "{", "gid", "}", ")", "of", "this", "file", ".", "As", "with", "python", "s", "C", "{", "os", ".", "chown", "}", "function", "you", "must", "pass", "both", "arguments", "so", "if", "you", "only", "want", "to", "change", "one", "use", "L", "{", "stat", "}", "first", "to", "retrieve", "the", "current", "owner", "and", "group", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/sftp_file.py#L244-L259
train
bitprophet/ssh
ssh/sftp_file.py
SFTPFile.utime
def utime(self, times): """ Set the access and modified times of this file. If C{times} is C{None}, then the file's access and modified times are set to the current time. Otherwise, C{times} must be a 2-tuple of numbers, of the form C{(atime, mtime)}, which is used to set the access and modified times, respectively. This bizarre API is mimicked from python for the sake of consistency -- I apologize. @param times: C{None} or a tuple of (access time, modified time) in standard internet epoch time (seconds since 01 January 1970 GMT) @type times: tuple(int) """ if times is None: times = (time.time(), time.time()) self.sftp._log(DEBUG, 'utime(%s, %r)' % (hexlify(self.handle), times)) attr = SFTPAttributes() attr.st_atime, attr.st_mtime = times self.sftp._request(CMD_FSETSTAT, self.handle, attr)
python
def utime(self, times): """ Set the access and modified times of this file. If C{times} is C{None}, then the file's access and modified times are set to the current time. Otherwise, C{times} must be a 2-tuple of numbers, of the form C{(atime, mtime)}, which is used to set the access and modified times, respectively. This bizarre API is mimicked from python for the sake of consistency -- I apologize. @param times: C{None} or a tuple of (access time, modified time) in standard internet epoch time (seconds since 01 January 1970 GMT) @type times: tuple(int) """ if times is None: times = (time.time(), time.time()) self.sftp._log(DEBUG, 'utime(%s, %r)' % (hexlify(self.handle), times)) attr = SFTPAttributes() attr.st_atime, attr.st_mtime = times self.sftp._request(CMD_FSETSTAT, self.handle, attr)
[ "def", "utime", "(", "self", ",", "times", ")", ":", "if", "times", "is", "None", ":", "times", "=", "(", "time", ".", "time", "(", ")", ",", "time", ".", "time", "(", ")", ")", "self", ".", "sftp", ".", "_log", "(", "DEBUG", ",", "'utime(%s, %r)'", "%", "(", "hexlify", "(", "self", ".", "handle", ")", ",", "times", ")", ")", "attr", "=", "SFTPAttributes", "(", ")", "attr", ".", "st_atime", ",", "attr", ".", "st_mtime", "=", "times", "self", ".", "sftp", ".", "_request", "(", "CMD_FSETSTAT", ",", "self", ".", "handle", ",", "attr", ")" ]
Set the access and modified times of this file. If C{times} is C{None}, then the file's access and modified times are set to the current time. Otherwise, C{times} must be a 2-tuple of numbers, of the form C{(atime, mtime)}, which is used to set the access and modified times, respectively. This bizarre API is mimicked from python for the sake of consistency -- I apologize. @param times: C{None} or a tuple of (access time, modified time) in standard internet epoch time (seconds since 01 January 1970 GMT) @type times: tuple(int)
[ "Set", "the", "access", "and", "modified", "times", "of", "this", "file", ".", "If", "C", "{", "times", "}", "is", "C", "{", "None", "}", "then", "the", "file", "s", "access", "and", "modified", "times", "are", "set", "to", "the", "current", "time", ".", "Otherwise", "C", "{", "times", "}", "must", "be", "a", "2", "-", "tuple", "of", "numbers", "of", "the", "form", "C", "{", "(", "atime", "mtime", ")", "}", "which", "is", "used", "to", "set", "the", "access", "and", "modified", "times", "respectively", ".", "This", "bizarre", "API", "is", "mimicked", "from", "python", "for", "the", "sake", "of", "consistency", "--", "I", "apologize", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/sftp_file.py#L261-L279
train
bitprophet/ssh
ssh/file.py
BufferedFile.flush
def flush(self): """ Write out any data in the write buffer. This may do nothing if write buffering is not turned on. """ self._write_all(self._wbuffer.getvalue()) self._wbuffer = StringIO() return
python
def flush(self): """ Write out any data in the write buffer. This may do nothing if write buffering is not turned on. """ self._write_all(self._wbuffer.getvalue()) self._wbuffer = StringIO() return
[ "def", "flush", "(", "self", ")", ":", "self", ".", "_write_all", "(", "self", ".", "_wbuffer", ".", "getvalue", "(", ")", ")", "self", ".", "_wbuffer", "=", "StringIO", "(", ")", "return" ]
Write out any data in the write buffer. This may do nothing if write buffering is not turned on.
[ "Write", "out", "any", "data", "in", "the", "write", "buffer", ".", "This", "may", "do", "nothing", "if", "write", "buffering", "is", "not", "turned", "on", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/file.py#L86-L93
train
bitprophet/ssh
ssh/file.py
BufferedFile.readline
def readline(self, size=None): """ Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. An empty string is returned only when EOF is encountered immediately. @note: Unlike stdio's C{fgets()}, the returned string contains null characters (C{'\\0'}) if they occurred in the input. @param size: maximum length of returned string. @type size: int @return: next line of the file, or an empty string if the end of the file has been reached. @rtype: str """ # it's almost silly how complex this function is. if self._closed: raise IOError('File is closed') if not (self._flags & self.FLAG_READ): raise IOError('File not open for reading') line = self._rbuffer while True: if self._at_trailing_cr and (self._flags & self.FLAG_UNIVERSAL_NEWLINE) and (len(line) > 0): # edge case: the newline may be '\r\n' and we may have read # only the first '\r' last time. if line[0] == '\n': line = line[1:] self._record_newline('\r\n') else: self._record_newline('\r') self._at_trailing_cr = False # check size before looking for a linefeed, in case we already have # enough. if (size is not None) and (size >= 0): if len(line) >= size: # truncate line and return self._rbuffer = line[size:] line = line[:size] self._pos += len(line) return line n = size - len(line) else: n = self._bufsize if ('\n' in line) or ((self._flags & self.FLAG_UNIVERSAL_NEWLINE) and ('\r' in line)): break try: new_data = self._read(n) except EOFError: new_data = None if (new_data is None) or (len(new_data) == 0): self._rbuffer = '' self._pos += len(line) return line line += new_data self._realpos += len(new_data) # find the newline pos = line.find('\n') if self._flags & self.FLAG_UNIVERSAL_NEWLINE: rpos = line.find('\r') if (rpos >= 0) and ((rpos < pos) or (pos < 0)): pos = rpos xpos = pos + 1 if (line[pos] == '\r') and (xpos < len(line)) and (line[xpos] == '\n'): xpos += 1 self._rbuffer = line[xpos:] lf = line[pos:xpos] line = line[:pos] + '\n' if (len(self._rbuffer) == 0) and (lf == '\r'): # we could read the line up to a '\r' and there could still be a # '\n' following that we read next time. note that and eat it. self._at_trailing_cr = True else: self._record_newline(lf) self._pos += len(line) return line
python
def readline(self, size=None): """ Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. An empty string is returned only when EOF is encountered immediately. @note: Unlike stdio's C{fgets()}, the returned string contains null characters (C{'\\0'}) if they occurred in the input. @param size: maximum length of returned string. @type size: int @return: next line of the file, or an empty string if the end of the file has been reached. @rtype: str """ # it's almost silly how complex this function is. if self._closed: raise IOError('File is closed') if not (self._flags & self.FLAG_READ): raise IOError('File not open for reading') line = self._rbuffer while True: if self._at_trailing_cr and (self._flags & self.FLAG_UNIVERSAL_NEWLINE) and (len(line) > 0): # edge case: the newline may be '\r\n' and we may have read # only the first '\r' last time. if line[0] == '\n': line = line[1:] self._record_newline('\r\n') else: self._record_newline('\r') self._at_trailing_cr = False # check size before looking for a linefeed, in case we already have # enough. if (size is not None) and (size >= 0): if len(line) >= size: # truncate line and return self._rbuffer = line[size:] line = line[:size] self._pos += len(line) return line n = size - len(line) else: n = self._bufsize if ('\n' in line) or ((self._flags & self.FLAG_UNIVERSAL_NEWLINE) and ('\r' in line)): break try: new_data = self._read(n) except EOFError: new_data = None if (new_data is None) or (len(new_data) == 0): self._rbuffer = '' self._pos += len(line) return line line += new_data self._realpos += len(new_data) # find the newline pos = line.find('\n') if self._flags & self.FLAG_UNIVERSAL_NEWLINE: rpos = line.find('\r') if (rpos >= 0) and ((rpos < pos) or (pos < 0)): pos = rpos xpos = pos + 1 if (line[pos] == '\r') and (xpos < len(line)) and (line[xpos] == '\n'): xpos += 1 self._rbuffer = line[xpos:] lf = line[pos:xpos] line = line[:pos] + '\n' if (len(self._rbuffer) == 0) and (lf == '\r'): # we could read the line up to a '\r' and there could still be a # '\n' following that we read next time. note that and eat it. self._at_trailing_cr = True else: self._record_newline(lf) self._pos += len(line) return line
[ "def", "readline", "(", "self", ",", "size", "=", "None", ")", ":", "# it's almost silly how complex this function is.", "if", "self", ".", "_closed", ":", "raise", "IOError", "(", "'File is closed'", ")", "if", "not", "(", "self", ".", "_flags", "&", "self", ".", "FLAG_READ", ")", ":", "raise", "IOError", "(", "'File not open for reading'", ")", "line", "=", "self", ".", "_rbuffer", "while", "True", ":", "if", "self", ".", "_at_trailing_cr", "and", "(", "self", ".", "_flags", "&", "self", ".", "FLAG_UNIVERSAL_NEWLINE", ")", "and", "(", "len", "(", "line", ")", ">", "0", ")", ":", "# edge case: the newline may be '\\r\\n' and we may have read", "# only the first '\\r' last time.", "if", "line", "[", "0", "]", "==", "'\\n'", ":", "line", "=", "line", "[", "1", ":", "]", "self", ".", "_record_newline", "(", "'\\r\\n'", ")", "else", ":", "self", ".", "_record_newline", "(", "'\\r'", ")", "self", ".", "_at_trailing_cr", "=", "False", "# check size before looking for a linefeed, in case we already have", "# enough.", "if", "(", "size", "is", "not", "None", ")", "and", "(", "size", ">=", "0", ")", ":", "if", "len", "(", "line", ")", ">=", "size", ":", "# truncate line and return", "self", ".", "_rbuffer", "=", "line", "[", "size", ":", "]", "line", "=", "line", "[", ":", "size", "]", "self", ".", "_pos", "+=", "len", "(", "line", ")", "return", "line", "n", "=", "size", "-", "len", "(", "line", ")", "else", ":", "n", "=", "self", ".", "_bufsize", "if", "(", "'\\n'", "in", "line", ")", "or", "(", "(", "self", ".", "_flags", "&", "self", ".", "FLAG_UNIVERSAL_NEWLINE", ")", "and", "(", "'\\r'", "in", "line", ")", ")", ":", "break", "try", ":", "new_data", "=", "self", ".", "_read", "(", "n", ")", "except", "EOFError", ":", "new_data", "=", "None", "if", "(", "new_data", "is", "None", ")", "or", "(", "len", "(", "new_data", ")", "==", "0", ")", ":", "self", ".", "_rbuffer", "=", "''", "self", ".", "_pos", "+=", "len", "(", "line", ")", "return", "line", "line", "+=", "new_data", "self", ".", "_realpos", "+=", "len", "(", "new_data", ")", "# find the newline", "pos", "=", "line", ".", "find", "(", "'\\n'", ")", "if", "self", ".", "_flags", "&", "self", ".", "FLAG_UNIVERSAL_NEWLINE", ":", "rpos", "=", "line", ".", "find", "(", "'\\r'", ")", "if", "(", "rpos", ">=", "0", ")", "and", "(", "(", "rpos", "<", "pos", ")", "or", "(", "pos", "<", "0", ")", ")", ":", "pos", "=", "rpos", "xpos", "=", "pos", "+", "1", "if", "(", "line", "[", "pos", "]", "==", "'\\r'", ")", "and", "(", "xpos", "<", "len", "(", "line", ")", ")", "and", "(", "line", "[", "xpos", "]", "==", "'\\n'", ")", ":", "xpos", "+=", "1", "self", ".", "_rbuffer", "=", "line", "[", "xpos", ":", "]", "lf", "=", "line", "[", "pos", ":", "xpos", "]", "line", "=", "line", "[", ":", "pos", "]", "+", "'\\n'", "if", "(", "len", "(", "self", ".", "_rbuffer", ")", "==", "0", ")", "and", "(", "lf", "==", "'\\r'", ")", ":", "# we could read the line up to a '\\r' and there could still be a", "# '\\n' following that we read next time. note that and eat it.", "self", ".", "_at_trailing_cr", "=", "True", "else", ":", "self", ".", "_record_newline", "(", "lf", ")", "self", ".", "_pos", "+=", "len", "(", "line", ")", "return", "line" ]
Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. An empty string is returned only when EOF is encountered immediately. @note: Unlike stdio's C{fgets()}, the returned string contains null characters (C{'\\0'}) if they occurred in the input. @param size: maximum length of returned string. @type size: int @return: next line of the file, or an empty string if the end of the file has been reached. @rtype: str
[ "Read", "one", "entire", "line", "from", "the", "file", ".", "A", "trailing", "newline", "character", "is", "kept", "in", "the", "string", "(", "but", "may", "be", "absent", "when", "a", "file", "ends", "with", "an", "incomplete", "line", ")", ".", "If", "the", "size", "argument", "is", "present", "and", "non", "-", "negative", "it", "is", "a", "maximum", "byte", "count", "(", "including", "the", "trailing", "newline", ")", "and", "an", "incomplete", "line", "may", "be", "returned", ".", "An", "empty", "string", "is", "returned", "only", "when", "EOF", "is", "encountered", "immediately", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/file.py#L165-L242
train
bitprophet/ssh
ssh/file.py
BufferedFile._set_mode
def _set_mode(self, mode='r', bufsize=-1): """ Subclasses call this method to initialize the BufferedFile. """ # set bufsize in any event, because it's used for readline(). self._bufsize = self._DEFAULT_BUFSIZE if bufsize < 0: # do no buffering by default, because otherwise writes will get # buffered in a way that will probably confuse people. bufsize = 0 if bufsize == 1: # apparently, line buffering only affects writes. reads are only # buffered if you call readline (directly or indirectly: iterating # over a file will indirectly call readline). self._flags |= self.FLAG_BUFFERED | self.FLAG_LINE_BUFFERED elif bufsize > 1: self._bufsize = bufsize self._flags |= self.FLAG_BUFFERED self._flags &= ~self.FLAG_LINE_BUFFERED elif bufsize == 0: # unbuffered self._flags &= ~(self.FLAG_BUFFERED | self.FLAG_LINE_BUFFERED) if ('r' in mode) or ('+' in mode): self._flags |= self.FLAG_READ if ('w' in mode) or ('+' in mode): self._flags |= self.FLAG_WRITE if ('a' in mode): self._flags |= self.FLAG_WRITE | self.FLAG_APPEND self._size = self._get_size() self._pos = self._realpos = self._size if ('b' in mode): self._flags |= self.FLAG_BINARY if ('U' in mode): self._flags |= self.FLAG_UNIVERSAL_NEWLINE # built-in file objects have this attribute to store which kinds of # line terminations they've seen: # <http://www.python.org/doc/current/lib/built-in-funcs.html> self.newlines = None
python
def _set_mode(self, mode='r', bufsize=-1): """ Subclasses call this method to initialize the BufferedFile. """ # set bufsize in any event, because it's used for readline(). self._bufsize = self._DEFAULT_BUFSIZE if bufsize < 0: # do no buffering by default, because otherwise writes will get # buffered in a way that will probably confuse people. bufsize = 0 if bufsize == 1: # apparently, line buffering only affects writes. reads are only # buffered if you call readline (directly or indirectly: iterating # over a file will indirectly call readline). self._flags |= self.FLAG_BUFFERED | self.FLAG_LINE_BUFFERED elif bufsize > 1: self._bufsize = bufsize self._flags |= self.FLAG_BUFFERED self._flags &= ~self.FLAG_LINE_BUFFERED elif bufsize == 0: # unbuffered self._flags &= ~(self.FLAG_BUFFERED | self.FLAG_LINE_BUFFERED) if ('r' in mode) or ('+' in mode): self._flags |= self.FLAG_READ if ('w' in mode) or ('+' in mode): self._flags |= self.FLAG_WRITE if ('a' in mode): self._flags |= self.FLAG_WRITE | self.FLAG_APPEND self._size = self._get_size() self._pos = self._realpos = self._size if ('b' in mode): self._flags |= self.FLAG_BINARY if ('U' in mode): self._flags |= self.FLAG_UNIVERSAL_NEWLINE # built-in file objects have this attribute to store which kinds of # line terminations they've seen: # <http://www.python.org/doc/current/lib/built-in-funcs.html> self.newlines = None
[ "def", "_set_mode", "(", "self", ",", "mode", "=", "'r'", ",", "bufsize", "=", "-", "1", ")", ":", "# set bufsize in any event, because it's used for readline().", "self", ".", "_bufsize", "=", "self", ".", "_DEFAULT_BUFSIZE", "if", "bufsize", "<", "0", ":", "# do no buffering by default, because otherwise writes will get", "# buffered in a way that will probably confuse people.", "bufsize", "=", "0", "if", "bufsize", "==", "1", ":", "# apparently, line buffering only affects writes. reads are only", "# buffered if you call readline (directly or indirectly: iterating", "# over a file will indirectly call readline).", "self", ".", "_flags", "|=", "self", ".", "FLAG_BUFFERED", "|", "self", ".", "FLAG_LINE_BUFFERED", "elif", "bufsize", ">", "1", ":", "self", ".", "_bufsize", "=", "bufsize", "self", ".", "_flags", "|=", "self", ".", "FLAG_BUFFERED", "self", ".", "_flags", "&=", "~", "self", ".", "FLAG_LINE_BUFFERED", "elif", "bufsize", "==", "0", ":", "# unbuffered", "self", ".", "_flags", "&=", "~", "(", "self", ".", "FLAG_BUFFERED", "|", "self", ".", "FLAG_LINE_BUFFERED", ")", "if", "(", "'r'", "in", "mode", ")", "or", "(", "'+'", "in", "mode", ")", ":", "self", ".", "_flags", "|=", "self", ".", "FLAG_READ", "if", "(", "'w'", "in", "mode", ")", "or", "(", "'+'", "in", "mode", ")", ":", "self", ".", "_flags", "|=", "self", ".", "FLAG_WRITE", "if", "(", "'a'", "in", "mode", ")", ":", "self", ".", "_flags", "|=", "self", ".", "FLAG_WRITE", "|", "self", ".", "FLAG_APPEND", "self", ".", "_size", "=", "self", ".", "_get_size", "(", ")", "self", ".", "_pos", "=", "self", ".", "_realpos", "=", "self", ".", "_size", "if", "(", "'b'", "in", "mode", ")", ":", "self", ".", "_flags", "|=", "self", ".", "FLAG_BINARY", "if", "(", "'U'", "in", "mode", ")", ":", "self", ".", "_flags", "|=", "self", ".", "FLAG_UNIVERSAL_NEWLINE", "# built-in file objects have this attribute to store which kinds of", "# line terminations they've seen:", "# <http://www.python.org/doc/current/lib/built-in-funcs.html>", "self", ".", "newlines", "=", "None" ]
Subclasses call this method to initialize the BufferedFile.
[ "Subclasses", "call", "this", "method", "to", "initialize", "the", "BufferedFile", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/file.py#L391-L429
train
bitprophet/ssh
ssh/sftp_client.py
SFTPClient.from_transport
def from_transport(cls, t): """ Create an SFTP client channel from an open L{Transport}. @param t: an open L{Transport} which is already authenticated @type t: L{Transport} @return: a new L{SFTPClient} object, referring to an sftp session (channel) across the transport @rtype: L{SFTPClient} """ chan = t.open_session() if chan is None: return None chan.invoke_subsystem('sftp') return cls(chan)
python
def from_transport(cls, t): """ Create an SFTP client channel from an open L{Transport}. @param t: an open L{Transport} which is already authenticated @type t: L{Transport} @return: a new L{SFTPClient} object, referring to an sftp session (channel) across the transport @rtype: L{SFTPClient} """ chan = t.open_session() if chan is None: return None chan.invoke_subsystem('sftp') return cls(chan)
[ "def", "from_transport", "(", "cls", ",", "t", ")", ":", "chan", "=", "t", ".", "open_session", "(", ")", "if", "chan", "is", "None", ":", "return", "None", "chan", ".", "invoke_subsystem", "(", "'sftp'", ")", "return", "cls", "(", "chan", ")" ]
Create an SFTP client channel from an open L{Transport}. @param t: an open L{Transport} which is already authenticated @type t: L{Transport} @return: a new L{SFTPClient} object, referring to an sftp session (channel) across the transport @rtype: L{SFTPClient}
[ "Create", "an", "SFTP", "client", "channel", "from", "an", "open", "L", "{", "Transport", "}", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/sftp_client.py#L92-L106
train
bitprophet/ssh
ssh/sftp_client.py
SFTPClient.listdir_attr
def listdir_attr(self, path='.'): """ Return a list containing L{SFTPAttributes} objects corresponding to files in the given C{path}. The list is in arbitrary order. It does not include the special entries C{'.'} and C{'..'} even if they are present in the folder. The returned L{SFTPAttributes} objects will each have an additional field: C{longname}, which may contain a formatted string of the file's attributes, in unix format. The content of this string will probably depend on the SFTP server implementation. @param path: path to list (defaults to C{'.'}) @type path: str @return: list of attributes @rtype: list of L{SFTPAttributes} @since: 1.2 """ path = self._adjust_cwd(path) self._log(DEBUG, 'listdir(%r)' % path) t, msg = self._request(CMD_OPENDIR, path) if t != CMD_HANDLE: raise SFTPError('Expected handle') handle = msg.get_string() filelist = [] while True: try: t, msg = self._request(CMD_READDIR, handle) except EOFError, e: # done with handle break if t != CMD_NAME: raise SFTPError('Expected name response') count = msg.get_int() for i in range(count): filename = _to_unicode(msg.get_string()) longname = _to_unicode(msg.get_string()) attr = SFTPAttributes._from_msg(msg, filename, longname) if (filename != '.') and (filename != '..'): filelist.append(attr) self._request(CMD_CLOSE, handle) return filelist
python
def listdir_attr(self, path='.'): """ Return a list containing L{SFTPAttributes} objects corresponding to files in the given C{path}. The list is in arbitrary order. It does not include the special entries C{'.'} and C{'..'} even if they are present in the folder. The returned L{SFTPAttributes} objects will each have an additional field: C{longname}, which may contain a formatted string of the file's attributes, in unix format. The content of this string will probably depend on the SFTP server implementation. @param path: path to list (defaults to C{'.'}) @type path: str @return: list of attributes @rtype: list of L{SFTPAttributes} @since: 1.2 """ path = self._adjust_cwd(path) self._log(DEBUG, 'listdir(%r)' % path) t, msg = self._request(CMD_OPENDIR, path) if t != CMD_HANDLE: raise SFTPError('Expected handle') handle = msg.get_string() filelist = [] while True: try: t, msg = self._request(CMD_READDIR, handle) except EOFError, e: # done with handle break if t != CMD_NAME: raise SFTPError('Expected name response') count = msg.get_int() for i in range(count): filename = _to_unicode(msg.get_string()) longname = _to_unicode(msg.get_string()) attr = SFTPAttributes._from_msg(msg, filename, longname) if (filename != '.') and (filename != '..'): filelist.append(attr) self._request(CMD_CLOSE, handle) return filelist
[ "def", "listdir_attr", "(", "self", ",", "path", "=", "'.'", ")", ":", "path", "=", "self", ".", "_adjust_cwd", "(", "path", ")", "self", ".", "_log", "(", "DEBUG", ",", "'listdir(%r)'", "%", "path", ")", "t", ",", "msg", "=", "self", ".", "_request", "(", "CMD_OPENDIR", ",", "path", ")", "if", "t", "!=", "CMD_HANDLE", ":", "raise", "SFTPError", "(", "'Expected handle'", ")", "handle", "=", "msg", ".", "get_string", "(", ")", "filelist", "=", "[", "]", "while", "True", ":", "try", ":", "t", ",", "msg", "=", "self", ".", "_request", "(", "CMD_READDIR", ",", "handle", ")", "except", "EOFError", ",", "e", ":", "# done with handle", "break", "if", "t", "!=", "CMD_NAME", ":", "raise", "SFTPError", "(", "'Expected name response'", ")", "count", "=", "msg", ".", "get_int", "(", ")", "for", "i", "in", "range", "(", "count", ")", ":", "filename", "=", "_to_unicode", "(", "msg", ".", "get_string", "(", ")", ")", "longname", "=", "_to_unicode", "(", "msg", ".", "get_string", "(", ")", ")", "attr", "=", "SFTPAttributes", ".", "_from_msg", "(", "msg", ",", "filename", ",", "longname", ")", "if", "(", "filename", "!=", "'.'", ")", "and", "(", "filename", "!=", "'..'", ")", ":", "filelist", ".", "append", "(", "attr", ")", "self", ".", "_request", "(", "CMD_CLOSE", ",", "handle", ")", "return", "filelist" ]
Return a list containing L{SFTPAttributes} objects corresponding to files in the given C{path}. The list is in arbitrary order. It does not include the special entries C{'.'} and C{'..'} even if they are present in the folder. The returned L{SFTPAttributes} objects will each have an additional field: C{longname}, which may contain a formatted string of the file's attributes, in unix format. The content of this string will probably depend on the SFTP server implementation. @param path: path to list (defaults to C{'.'}) @type path: str @return: list of attributes @rtype: list of L{SFTPAttributes} @since: 1.2
[ "Return", "a", "list", "containing", "L", "{", "SFTPAttributes", "}", "objects", "corresponding", "to", "files", "in", "the", "given", "C", "{", "path", "}", ".", "The", "list", "is", "in", "arbitrary", "order", ".", "It", "does", "not", "include", "the", "special", "entries", "C", "{", ".", "}", "and", "C", "{", "..", "}", "even", "if", "they", "are", "present", "in", "the", "folder", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/sftp_client.py#L152-L194
train
bitprophet/ssh
ssh/sftp_client.py
SFTPClient.remove
def remove(self, path): """ Remove the file at the given path. This only works on files; for removing folders (directories), use L{rmdir}. @param path: path (absolute or relative) of the file to remove @type path: str @raise IOError: if the path refers to a folder (directory) """ path = self._adjust_cwd(path) self._log(DEBUG, 'remove(%r)' % path) self._request(CMD_REMOVE, path)
python
def remove(self, path): """ Remove the file at the given path. This only works on files; for removing folders (directories), use L{rmdir}. @param path: path (absolute or relative) of the file to remove @type path: str @raise IOError: if the path refers to a folder (directory) """ path = self._adjust_cwd(path) self._log(DEBUG, 'remove(%r)' % path) self._request(CMD_REMOVE, path)
[ "def", "remove", "(", "self", ",", "path", ")", ":", "path", "=", "self", ".", "_adjust_cwd", "(", "path", ")", "self", ".", "_log", "(", "DEBUG", ",", "'remove(%r)'", "%", "path", ")", "self", ".", "_request", "(", "CMD_REMOVE", ",", "path", ")" ]
Remove the file at the given path. This only works on files; for removing folders (directories), use L{rmdir}. @param path: path (absolute or relative) of the file to remove @type path: str @raise IOError: if the path refers to a folder (directory)
[ "Remove", "the", "file", "at", "the", "given", "path", ".", "This", "only", "works", "on", "files", ";", "for", "removing", "folders", "(", "directories", ")", "use", "L", "{", "rmdir", "}", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/sftp_client.py#L255-L267
train
bitprophet/ssh
ssh/sftp_client.py
SFTPClient.rmdir
def rmdir(self, path): """ Remove the folder named C{path}. @param path: name of the folder to remove @type path: str """ path = self._adjust_cwd(path) self._log(DEBUG, 'rmdir(%r)' % path) self._request(CMD_RMDIR, path)
python
def rmdir(self, path): """ Remove the folder named C{path}. @param path: name of the folder to remove @type path: str """ path = self._adjust_cwd(path) self._log(DEBUG, 'rmdir(%r)' % path) self._request(CMD_RMDIR, path)
[ "def", "rmdir", "(", "self", ",", "path", ")", ":", "path", "=", "self", ".", "_adjust_cwd", "(", "path", ")", "self", ".", "_log", "(", "DEBUG", ",", "'rmdir(%r)'", "%", "path", ")", "self", ".", "_request", "(", "CMD_RMDIR", ",", "path", ")" ]
Remove the folder named C{path}. @param path: name of the folder to remove @type path: str
[ "Remove", "the", "folder", "named", "C", "{", "path", "}", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/sftp_client.py#L305-L314
train
bitprophet/ssh
ssh/sftp_client.py
SFTPClient.stat
def stat(self, path): """ Retrieve information about a file on the remote system. The return value is an object whose attributes correspond to the attributes of python's C{stat} structure as returned by C{os.stat}, except that it contains fewer fields. An SFTP server may return as much or as little info as it wants, so the results may vary from server to server. Unlike a python C{stat} object, the result may not be accessed as a tuple. This is mostly due to the author's slack factor. The fields supported are: C{st_mode}, C{st_size}, C{st_uid}, C{st_gid}, C{st_atime}, and C{st_mtime}. @param path: the filename to stat @type path: str @return: an object containing attributes about the given file @rtype: SFTPAttributes """ path = self._adjust_cwd(path) self._log(DEBUG, 'stat(%r)' % path) t, msg = self._request(CMD_STAT, path) if t != CMD_ATTRS: raise SFTPError('Expected attributes') return SFTPAttributes._from_msg(msg)
python
def stat(self, path): """ Retrieve information about a file on the remote system. The return value is an object whose attributes correspond to the attributes of python's C{stat} structure as returned by C{os.stat}, except that it contains fewer fields. An SFTP server may return as much or as little info as it wants, so the results may vary from server to server. Unlike a python C{stat} object, the result may not be accessed as a tuple. This is mostly due to the author's slack factor. The fields supported are: C{st_mode}, C{st_size}, C{st_uid}, C{st_gid}, C{st_atime}, and C{st_mtime}. @param path: the filename to stat @type path: str @return: an object containing attributes about the given file @rtype: SFTPAttributes """ path = self._adjust_cwd(path) self._log(DEBUG, 'stat(%r)' % path) t, msg = self._request(CMD_STAT, path) if t != CMD_ATTRS: raise SFTPError('Expected attributes') return SFTPAttributes._from_msg(msg)
[ "def", "stat", "(", "self", ",", "path", ")", ":", "path", "=", "self", ".", "_adjust_cwd", "(", "path", ")", "self", ".", "_log", "(", "DEBUG", ",", "'stat(%r)'", "%", "path", ")", "t", ",", "msg", "=", "self", ".", "_request", "(", "CMD_STAT", ",", "path", ")", "if", "t", "!=", "CMD_ATTRS", ":", "raise", "SFTPError", "(", "'Expected attributes'", ")", "return", "SFTPAttributes", ".", "_from_msg", "(", "msg", ")" ]
Retrieve information about a file on the remote system. The return value is an object whose attributes correspond to the attributes of python's C{stat} structure as returned by C{os.stat}, except that it contains fewer fields. An SFTP server may return as much or as little info as it wants, so the results may vary from server to server. Unlike a python C{stat} object, the result may not be accessed as a tuple. This is mostly due to the author's slack factor. The fields supported are: C{st_mode}, C{st_size}, C{st_uid}, C{st_gid}, C{st_atime}, and C{st_mtime}. @param path: the filename to stat @type path: str @return: an object containing attributes about the given file @rtype: SFTPAttributes
[ "Retrieve", "information", "about", "a", "file", "on", "the", "remote", "system", ".", "The", "return", "value", "is", "an", "object", "whose", "attributes", "correspond", "to", "the", "attributes", "of", "python", "s", "C", "{", "stat", "}", "structure", "as", "returned", "by", "C", "{", "os", ".", "stat", "}", "except", "that", "it", "contains", "fewer", "fields", ".", "An", "SFTP", "server", "may", "return", "as", "much", "or", "as", "little", "info", "as", "it", "wants", "so", "the", "results", "may", "vary", "from", "server", "to", "server", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/sftp_client.py#L316-L340
train
bitprophet/ssh
ssh/sftp_client.py
SFTPClient.lstat
def lstat(self, path): """ Retrieve information about a file on the remote system, without following symbolic links (shortcuts). This otherwise behaves exactly the same as L{stat}. @param path: the filename to stat @type path: str @return: an object containing attributes about the given file @rtype: SFTPAttributes """ path = self._adjust_cwd(path) self._log(DEBUG, 'lstat(%r)' % path) t, msg = self._request(CMD_LSTAT, path) if t != CMD_ATTRS: raise SFTPError('Expected attributes') return SFTPAttributes._from_msg(msg)
python
def lstat(self, path): """ Retrieve information about a file on the remote system, without following symbolic links (shortcuts). This otherwise behaves exactly the same as L{stat}. @param path: the filename to stat @type path: str @return: an object containing attributes about the given file @rtype: SFTPAttributes """ path = self._adjust_cwd(path) self._log(DEBUG, 'lstat(%r)' % path) t, msg = self._request(CMD_LSTAT, path) if t != CMD_ATTRS: raise SFTPError('Expected attributes') return SFTPAttributes._from_msg(msg)
[ "def", "lstat", "(", "self", ",", "path", ")", ":", "path", "=", "self", ".", "_adjust_cwd", "(", "path", ")", "self", ".", "_log", "(", "DEBUG", ",", "'lstat(%r)'", "%", "path", ")", "t", ",", "msg", "=", "self", ".", "_request", "(", "CMD_LSTAT", ",", "path", ")", "if", "t", "!=", "CMD_ATTRS", ":", "raise", "SFTPError", "(", "'Expected attributes'", ")", "return", "SFTPAttributes", ".", "_from_msg", "(", "msg", ")" ]
Retrieve information about a file on the remote system, without following symbolic links (shortcuts). This otherwise behaves exactly the same as L{stat}. @param path: the filename to stat @type path: str @return: an object containing attributes about the given file @rtype: SFTPAttributes
[ "Retrieve", "information", "about", "a", "file", "on", "the", "remote", "system", "without", "following", "symbolic", "links", "(", "shortcuts", ")", ".", "This", "otherwise", "behaves", "exactly", "the", "same", "as", "L", "{", "stat", "}", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/sftp_client.py#L342-L358
train
bitprophet/ssh
ssh/sftp_client.py
SFTPClient.symlink
def symlink(self, source, dest): """ Create a symbolic link (shortcut) of the C{source} path at C{destination}. @param source: path of the original file @type source: str @param dest: path of the newly created symlink @type dest: str """ dest = self._adjust_cwd(dest) self._log(DEBUG, 'symlink(%r, %r)' % (source, dest)) if type(source) is unicode: source = source.encode('utf-8') self._request(CMD_SYMLINK, source, dest)
python
def symlink(self, source, dest): """ Create a symbolic link (shortcut) of the C{source} path at C{destination}. @param source: path of the original file @type source: str @param dest: path of the newly created symlink @type dest: str """ dest = self._adjust_cwd(dest) self._log(DEBUG, 'symlink(%r, %r)' % (source, dest)) if type(source) is unicode: source = source.encode('utf-8') self._request(CMD_SYMLINK, source, dest)
[ "def", "symlink", "(", "self", ",", "source", ",", "dest", ")", ":", "dest", "=", "self", ".", "_adjust_cwd", "(", "dest", ")", "self", ".", "_log", "(", "DEBUG", ",", "'symlink(%r, %r)'", "%", "(", "source", ",", "dest", ")", ")", "if", "type", "(", "source", ")", "is", "unicode", ":", "source", "=", "source", ".", "encode", "(", "'utf-8'", ")", "self", ".", "_request", "(", "CMD_SYMLINK", ",", "source", ",", "dest", ")" ]
Create a symbolic link (shortcut) of the C{source} path at C{destination}. @param source: path of the original file @type source: str @param dest: path of the newly created symlink @type dest: str
[ "Create", "a", "symbolic", "link", "(", "shortcut", ")", "of", "the", "C", "{", "source", "}", "path", "at", "C", "{", "destination", "}", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/sftp_client.py#L360-L374
train
bitprophet/ssh
ssh/sftp_client.py
SFTPClient.chmod
def chmod(self, path, mode): """ Change the mode (permissions) of a file. The permissions are unix-style and identical to those used by python's C{os.chmod} function. @param path: path of the file to change the permissions of @type path: str @param mode: new permissions @type mode: int """ path = self._adjust_cwd(path) self._log(DEBUG, 'chmod(%r, %r)' % (path, mode)) attr = SFTPAttributes() attr.st_mode = mode self._request(CMD_SETSTAT, path, attr)
python
def chmod(self, path, mode): """ Change the mode (permissions) of a file. The permissions are unix-style and identical to those used by python's C{os.chmod} function. @param path: path of the file to change the permissions of @type path: str @param mode: new permissions @type mode: int """ path = self._adjust_cwd(path) self._log(DEBUG, 'chmod(%r, %r)' % (path, mode)) attr = SFTPAttributes() attr.st_mode = mode self._request(CMD_SETSTAT, path, attr)
[ "def", "chmod", "(", "self", ",", "path", ",", "mode", ")", ":", "path", "=", "self", ".", "_adjust_cwd", "(", "path", ")", "self", ".", "_log", "(", "DEBUG", ",", "'chmod(%r, %r)'", "%", "(", "path", ",", "mode", ")", ")", "attr", "=", "SFTPAttributes", "(", ")", "attr", ".", "st_mode", "=", "mode", "self", ".", "_request", "(", "CMD_SETSTAT", ",", "path", ",", "attr", ")" ]
Change the mode (permissions) of a file. The permissions are unix-style and identical to those used by python's C{os.chmod} function. @param path: path of the file to change the permissions of @type path: str @param mode: new permissions @type mode: int
[ "Change", "the", "mode", "(", "permissions", ")", "of", "a", "file", ".", "The", "permissions", "are", "unix", "-", "style", "and", "identical", "to", "those", "used", "by", "python", "s", "C", "{", "os", ".", "chmod", "}", "function", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/sftp_client.py#L376-L391
train
bitprophet/ssh
ssh/sftp_client.py
SFTPClient.readlink
def readlink(self, path): """ Return the target of a symbolic link (shortcut). You can use L{symlink} to create these. The result may be either an absolute or relative pathname. @param path: path of the symbolic link file @type path: str @return: target path @rtype: str """ path = self._adjust_cwd(path) self._log(DEBUG, 'readlink(%r)' % path) t, msg = self._request(CMD_READLINK, path) if t != CMD_NAME: raise SFTPError('Expected name response') count = msg.get_int() if count == 0: return None if count != 1: raise SFTPError('Readlink returned %d results' % count) return _to_unicode(msg.get_string())
python
def readlink(self, path): """ Return the target of a symbolic link (shortcut). You can use L{symlink} to create these. The result may be either an absolute or relative pathname. @param path: path of the symbolic link file @type path: str @return: target path @rtype: str """ path = self._adjust_cwd(path) self._log(DEBUG, 'readlink(%r)' % path) t, msg = self._request(CMD_READLINK, path) if t != CMD_NAME: raise SFTPError('Expected name response') count = msg.get_int() if count == 0: return None if count != 1: raise SFTPError('Readlink returned %d results' % count) return _to_unicode(msg.get_string())
[ "def", "readlink", "(", "self", ",", "path", ")", ":", "path", "=", "self", ".", "_adjust_cwd", "(", "path", ")", "self", ".", "_log", "(", "DEBUG", ",", "'readlink(%r)'", "%", "path", ")", "t", ",", "msg", "=", "self", ".", "_request", "(", "CMD_READLINK", ",", "path", ")", "if", "t", "!=", "CMD_NAME", ":", "raise", "SFTPError", "(", "'Expected name response'", ")", "count", "=", "msg", ".", "get_int", "(", ")", "if", "count", "==", "0", ":", "return", "None", "if", "count", "!=", "1", ":", "raise", "SFTPError", "(", "'Readlink returned %d results'", "%", "count", ")", "return", "_to_unicode", "(", "msg", ".", "get_string", "(", ")", ")" ]
Return the target of a symbolic link (shortcut). You can use L{symlink} to create these. The result may be either an absolute or relative pathname. @param path: path of the symbolic link file @type path: str @return: target path @rtype: str
[ "Return", "the", "target", "of", "a", "symbolic", "link", "(", "shortcut", ")", ".", "You", "can", "use", "L", "{", "symlink", "}", "to", "create", "these", ".", "The", "result", "may", "be", "either", "an", "absolute", "or", "relative", "pathname", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/sftp_client.py#L453-L474
train
bitprophet/ssh
ssh/sftp_client.py
SFTPClient.normalize
def normalize(self, path): """ Return the normalized path (on the server) of a given path. This can be used to quickly resolve symbolic links or determine what the server is considering to be the "current folder" (by passing C{'.'} as C{path}). @param path: path to be normalized @type path: str @return: normalized form of the given path @rtype: str @raise IOError: if the path can't be resolved on the server """ path = self._adjust_cwd(path) self._log(DEBUG, 'normalize(%r)' % path) t, msg = self._request(CMD_REALPATH, path) if t != CMD_NAME: raise SFTPError('Expected name response') count = msg.get_int() if count != 1: raise SFTPError('Realpath returned %d results' % count) return _to_unicode(msg.get_string())
python
def normalize(self, path): """ Return the normalized path (on the server) of a given path. This can be used to quickly resolve symbolic links or determine what the server is considering to be the "current folder" (by passing C{'.'} as C{path}). @param path: path to be normalized @type path: str @return: normalized form of the given path @rtype: str @raise IOError: if the path can't be resolved on the server """ path = self._adjust_cwd(path) self._log(DEBUG, 'normalize(%r)' % path) t, msg = self._request(CMD_REALPATH, path) if t != CMD_NAME: raise SFTPError('Expected name response') count = msg.get_int() if count != 1: raise SFTPError('Realpath returned %d results' % count) return _to_unicode(msg.get_string())
[ "def", "normalize", "(", "self", ",", "path", ")", ":", "path", "=", "self", ".", "_adjust_cwd", "(", "path", ")", "self", ".", "_log", "(", "DEBUG", ",", "'normalize(%r)'", "%", "path", ")", "t", ",", "msg", "=", "self", ".", "_request", "(", "CMD_REALPATH", ",", "path", ")", "if", "t", "!=", "CMD_NAME", ":", "raise", "SFTPError", "(", "'Expected name response'", ")", "count", "=", "msg", ".", "get_int", "(", ")", "if", "count", "!=", "1", ":", "raise", "SFTPError", "(", "'Realpath returned %d results'", "%", "count", ")", "return", "_to_unicode", "(", "msg", ".", "get_string", "(", ")", ")" ]
Return the normalized path (on the server) of a given path. This can be used to quickly resolve symbolic links or determine what the server is considering to be the "current folder" (by passing C{'.'} as C{path}). @param path: path to be normalized @type path: str @return: normalized form of the given path @rtype: str @raise IOError: if the path can't be resolved on the server
[ "Return", "the", "normalized", "path", "(", "on", "the", "server", ")", "of", "a", "given", "path", ".", "This", "can", "be", "used", "to", "quickly", "resolve", "symbolic", "links", "or", "determine", "what", "the", "server", "is", "considering", "to", "be", "the", "current", "folder", "(", "by", "passing", "C", "{", ".", "}", "as", "C", "{", "path", "}", ")", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/sftp_client.py#L476-L498
train
bitprophet/ssh
ssh/sftp_client.py
SFTPClient.get
def get(self, remotepath, localpath, callback=None): """ Copy a remote file (C{remotepath}) from the SFTP server to the local host as C{localpath}. Any exception raised by operations will be passed through. This method is primarily provided as a convenience. @param remotepath: the remote file to copy @type remotepath: str @param localpath: the destination path on the local host @type localpath: str @param callback: optional callback function that accepts the bytes transferred so far and the total bytes to be transferred (since 1.7.4) @type callback: function(int, int) @since: 1.4 """ fr = self.file(remotepath, 'rb') file_size = self.stat(remotepath).st_size fr.prefetch() try: fl = file(localpath, 'wb') try: size = 0 while True: data = fr.read(32768) if len(data) == 0: break fl.write(data) size += len(data) if callback is not None: callback(size, file_size) finally: fl.close() finally: fr.close() s = os.stat(localpath) if s.st_size != size: raise IOError('size mismatch in get! %d != %d' % (s.st_size, size))
python
def get(self, remotepath, localpath, callback=None): """ Copy a remote file (C{remotepath}) from the SFTP server to the local host as C{localpath}. Any exception raised by operations will be passed through. This method is primarily provided as a convenience. @param remotepath: the remote file to copy @type remotepath: str @param localpath: the destination path on the local host @type localpath: str @param callback: optional callback function that accepts the bytes transferred so far and the total bytes to be transferred (since 1.7.4) @type callback: function(int, int) @since: 1.4 """ fr = self.file(remotepath, 'rb') file_size = self.stat(remotepath).st_size fr.prefetch() try: fl = file(localpath, 'wb') try: size = 0 while True: data = fr.read(32768) if len(data) == 0: break fl.write(data) size += len(data) if callback is not None: callback(size, file_size) finally: fl.close() finally: fr.close() s = os.stat(localpath) if s.st_size != size: raise IOError('size mismatch in get! %d != %d' % (s.st_size, size))
[ "def", "get", "(", "self", ",", "remotepath", ",", "localpath", ",", "callback", "=", "None", ")", ":", "fr", "=", "self", ".", "file", "(", "remotepath", ",", "'rb'", ")", "file_size", "=", "self", ".", "stat", "(", "remotepath", ")", ".", "st_size", "fr", ".", "prefetch", "(", ")", "try", ":", "fl", "=", "file", "(", "localpath", ",", "'wb'", ")", "try", ":", "size", "=", "0", "while", "True", ":", "data", "=", "fr", ".", "read", "(", "32768", ")", "if", "len", "(", "data", ")", "==", "0", ":", "break", "fl", ".", "write", "(", "data", ")", "size", "+=", "len", "(", "data", ")", "if", "callback", "is", "not", "None", ":", "callback", "(", "size", ",", "file_size", ")", "finally", ":", "fl", ".", "close", "(", ")", "finally", ":", "fr", ".", "close", "(", ")", "s", "=", "os", ".", "stat", "(", "localpath", ")", "if", "s", ".", "st_size", "!=", "size", ":", "raise", "IOError", "(", "'size mismatch in get! %d != %d'", "%", "(", "s", ".", "st_size", ",", "size", ")", ")" ]
Copy a remote file (C{remotepath}) from the SFTP server to the local host as C{localpath}. Any exception raised by operations will be passed through. This method is primarily provided as a convenience. @param remotepath: the remote file to copy @type remotepath: str @param localpath: the destination path on the local host @type localpath: str @param callback: optional callback function that accepts the bytes transferred so far and the total bytes to be transferred (since 1.7.4) @type callback: function(int, int) @since: 1.4
[ "Copy", "a", "remote", "file", "(", "C", "{", "remotepath", "}", ")", "from", "the", "SFTP", "server", "to", "the", "local", "host", "as", "C", "{", "localpath", "}", ".", "Any", "exception", "raised", "by", "operations", "will", "be", "passed", "through", ".", "This", "method", "is", "primarily", "provided", "as", "a", "convenience", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/sftp_client.py#L589-L627
train
bitprophet/ssh
ssh/sftp_client.py
SFTPClient._adjust_cwd
def _adjust_cwd(self, path): """ Return an adjusted path if we're emulating a "current working directory" for the server. """ if type(path) is unicode: path = path.encode('utf-8') if self._cwd is None: return path if (len(path) > 0) and (path[0] == '/'): # absolute path return path if self._cwd == '/': return self._cwd + path return self._cwd + '/' + path
python
def _adjust_cwd(self, path): """ Return an adjusted path if we're emulating a "current working directory" for the server. """ if type(path) is unicode: path = path.encode('utf-8') if self._cwd is None: return path if (len(path) > 0) and (path[0] == '/'): # absolute path return path if self._cwd == '/': return self._cwd + path return self._cwd + '/' + path
[ "def", "_adjust_cwd", "(", "self", ",", "path", ")", ":", "if", "type", "(", "path", ")", "is", "unicode", ":", "path", "=", "path", ".", "encode", "(", "'utf-8'", ")", "if", "self", ".", "_cwd", "is", "None", ":", "return", "path", "if", "(", "len", "(", "path", ")", ">", "0", ")", "and", "(", "path", "[", "0", "]", "==", "'/'", ")", ":", "# absolute path", "return", "path", "if", "self", ".", "_cwd", "==", "'/'", ":", "return", "self", ".", "_cwd", "+", "path", "return", "self", ".", "_cwd", "+", "'/'", "+", "path" ]
Return an adjusted path if we're emulating a "current working directory" for the server.
[ "Return", "an", "adjusted", "path", "if", "we", "re", "emulating", "a", "current", "working", "directory", "for", "the", "server", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/sftp_client.py#L714-L728
train
bitprophet/ssh
ssh/resource.py
ResourceManager.register
def register(self, obj, resource): """ Register a resource to be closed with an object is collected. When the given C{obj} is garbage-collected by the python interpreter, the C{resource} will be closed by having its C{close()} method called. Any exceptions are ignored. @param obj: the object to track @type obj: object @param resource: the resource to close when the object is collected @type resource: object """ def callback(ref): try: resource.close() except: pass del self._table[id(resource)] # keep the weakref in a table so it sticks around long enough to get # its callback called. :) self._table[id(resource)] = weakref.ref(obj, callback)
python
def register(self, obj, resource): """ Register a resource to be closed with an object is collected. When the given C{obj} is garbage-collected by the python interpreter, the C{resource} will be closed by having its C{close()} method called. Any exceptions are ignored. @param obj: the object to track @type obj: object @param resource: the resource to close when the object is collected @type resource: object """ def callback(ref): try: resource.close() except: pass del self._table[id(resource)] # keep the weakref in a table so it sticks around long enough to get # its callback called. :) self._table[id(resource)] = weakref.ref(obj, callback)
[ "def", "register", "(", "self", ",", "obj", ",", "resource", ")", ":", "def", "callback", "(", "ref", ")", ":", "try", ":", "resource", ".", "close", "(", ")", "except", ":", "pass", "del", "self", ".", "_table", "[", "id", "(", "resource", ")", "]", "# keep the weakref in a table so it sticks around long enough to get", "# its callback called. :)", "self", ".", "_table", "[", "id", "(", "resource", ")", "]", "=", "weakref", ".", "ref", "(", "obj", ",", "callback", ")" ]
Register a resource to be closed with an object is collected. When the given C{obj} is garbage-collected by the python interpreter, the C{resource} will be closed by having its C{close()} method called. Any exceptions are ignored. @param obj: the object to track @type obj: object @param resource: the resource to close when the object is collected @type resource: object
[ "Register", "a", "resource", "to", "be", "closed", "with", "an", "object", "is", "collected", ".", "When", "the", "given", "C", "{", "obj", "}", "is", "garbage", "-", "collected", "by", "the", "python", "interpreter", "the", "C", "{", "resource", "}", "will", "be", "closed", "by", "having", "its", "C", "{", "close", "()", "}", "method", "called", ".", "Any", "exceptions", "are", "ignored", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/resource.py#L46-L68
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray._request
def _request(self, method, path, data=None, reestablish_session=True): """Perform HTTP request for REST API.""" if path.startswith("http"): url = path # For cases where URL of different form is needed. else: url = self._format_path(path) headers = {"Content-Type": "application/json"} if self._user_agent: headers['User-Agent'] = self._user_agent body = json.dumps(data).encode("utf-8") try: response = requests.request(method, url, data=body, headers=headers, cookies=self._cookies, **self._request_kwargs) except requests.exceptions.RequestException as err: # error outside scope of HTTP status codes # e.g. unable to resolve domain name raise PureError(err.message) if response.status_code == 200: if "application/json" in response.headers.get("Content-Type", ""): if response.cookies: self._cookies.update(response.cookies) else: self._cookies.clear() content = response.json() if isinstance(content, list): content = ResponseList(content) elif isinstance(content, dict): content = ResponseDict(content) content.headers = response.headers return content raise PureError("Response not in JSON: " + response.text) elif response.status_code == 401 and reestablish_session: self._start_session() return self._request(method, path, data, False) elif response.status_code == 450 and self._renegotiate_rest_version: # Purity REST API version is incompatible. old_version = self._rest_version self._rest_version = self._choose_rest_version() if old_version == self._rest_version: # Got 450 error, but the rest version was supported # Something really unexpected happened. raise PureHTTPError(self._target, str(self._rest_version), response) return self._request(method, path, data, reestablish_session) else: raise PureHTTPError(self._target, str(self._rest_version), response)
python
def _request(self, method, path, data=None, reestablish_session=True): """Perform HTTP request for REST API.""" if path.startswith("http"): url = path # For cases where URL of different form is needed. else: url = self._format_path(path) headers = {"Content-Type": "application/json"} if self._user_agent: headers['User-Agent'] = self._user_agent body = json.dumps(data).encode("utf-8") try: response = requests.request(method, url, data=body, headers=headers, cookies=self._cookies, **self._request_kwargs) except requests.exceptions.RequestException as err: # error outside scope of HTTP status codes # e.g. unable to resolve domain name raise PureError(err.message) if response.status_code == 200: if "application/json" in response.headers.get("Content-Type", ""): if response.cookies: self._cookies.update(response.cookies) else: self._cookies.clear() content = response.json() if isinstance(content, list): content = ResponseList(content) elif isinstance(content, dict): content = ResponseDict(content) content.headers = response.headers return content raise PureError("Response not in JSON: " + response.text) elif response.status_code == 401 and reestablish_session: self._start_session() return self._request(method, path, data, False) elif response.status_code == 450 and self._renegotiate_rest_version: # Purity REST API version is incompatible. old_version = self._rest_version self._rest_version = self._choose_rest_version() if old_version == self._rest_version: # Got 450 error, but the rest version was supported # Something really unexpected happened. raise PureHTTPError(self._target, str(self._rest_version), response) return self._request(method, path, data, reestablish_session) else: raise PureHTTPError(self._target, str(self._rest_version), response)
[ "def", "_request", "(", "self", ",", "method", ",", "path", ",", "data", "=", "None", ",", "reestablish_session", "=", "True", ")", ":", "if", "path", ".", "startswith", "(", "\"http\"", ")", ":", "url", "=", "path", "# For cases where URL of different form is needed.", "else", ":", "url", "=", "self", ".", "_format_path", "(", "path", ")", "headers", "=", "{", "\"Content-Type\"", ":", "\"application/json\"", "}", "if", "self", ".", "_user_agent", ":", "headers", "[", "'User-Agent'", "]", "=", "self", ".", "_user_agent", "body", "=", "json", ".", "dumps", "(", "data", ")", ".", "encode", "(", "\"utf-8\"", ")", "try", ":", "response", "=", "requests", ".", "request", "(", "method", ",", "url", ",", "data", "=", "body", ",", "headers", "=", "headers", ",", "cookies", "=", "self", ".", "_cookies", ",", "*", "*", "self", ".", "_request_kwargs", ")", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "err", ":", "# error outside scope of HTTP status codes", "# e.g. unable to resolve domain name", "raise", "PureError", "(", "err", ".", "message", ")", "if", "response", ".", "status_code", "==", "200", ":", "if", "\"application/json\"", "in", "response", ".", "headers", ".", "get", "(", "\"Content-Type\"", ",", "\"\"", ")", ":", "if", "response", ".", "cookies", ":", "self", ".", "_cookies", ".", "update", "(", "response", ".", "cookies", ")", "else", ":", "self", ".", "_cookies", ".", "clear", "(", ")", "content", "=", "response", ".", "json", "(", ")", "if", "isinstance", "(", "content", ",", "list", ")", ":", "content", "=", "ResponseList", "(", "content", ")", "elif", "isinstance", "(", "content", ",", "dict", ")", ":", "content", "=", "ResponseDict", "(", "content", ")", "content", ".", "headers", "=", "response", ".", "headers", "return", "content", "raise", "PureError", "(", "\"Response not in JSON: \"", "+", "response", ".", "text", ")", "elif", "response", ".", "status_code", "==", "401", "and", "reestablish_session", ":", "self", ".", "_start_session", "(", ")", "return", "self", ".", "_request", "(", "method", ",", "path", ",", "data", ",", "False", ")", "elif", "response", ".", "status_code", "==", "450", "and", "self", ".", "_renegotiate_rest_version", ":", "# Purity REST API version is incompatible.", "old_version", "=", "self", ".", "_rest_version", "self", ".", "_rest_version", "=", "self", ".", "_choose_rest_version", "(", ")", "if", "old_version", "==", "self", ".", "_rest_version", ":", "# Got 450 error, but the rest version was supported", "# Something really unexpected happened.", "raise", "PureHTTPError", "(", "self", ".", "_target", ",", "str", "(", "self", ".", "_rest_version", ")", ",", "response", ")", "return", "self", ".", "_request", "(", "method", ",", "path", ",", "data", ",", "reestablish_session", ")", "else", ":", "raise", "PureHTTPError", "(", "self", ".", "_target", ",", "str", "(", "self", ".", "_rest_version", ")", ",", "response", ")" ]
Perform HTTP request for REST API.
[ "Perform", "HTTP", "request", "for", "REST", "API", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L149-L196
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray._check_rest_version
def _check_rest_version(self, version): """Validate a REST API version is supported by the library and target array.""" version = str(version) if version not in self.supported_rest_versions: msg = "Library is incompatible with REST API version {0}" raise ValueError(msg.format(version)) array_rest_versions = self._list_available_rest_versions() if version not in array_rest_versions: msg = "Array is incompatible with REST API version {0}" raise ValueError(msg.format(version)) return LooseVersion(version)
python
def _check_rest_version(self, version): """Validate a REST API version is supported by the library and target array.""" version = str(version) if version not in self.supported_rest_versions: msg = "Library is incompatible with REST API version {0}" raise ValueError(msg.format(version)) array_rest_versions = self._list_available_rest_versions() if version not in array_rest_versions: msg = "Array is incompatible with REST API version {0}" raise ValueError(msg.format(version)) return LooseVersion(version)
[ "def", "_check_rest_version", "(", "self", ",", "version", ")", ":", "version", "=", "str", "(", "version", ")", "if", "version", "not", "in", "self", ".", "supported_rest_versions", ":", "msg", "=", "\"Library is incompatible with REST API version {0}\"", "raise", "ValueError", "(", "msg", ".", "format", "(", "version", ")", ")", "array_rest_versions", "=", "self", ".", "_list_available_rest_versions", "(", ")", "if", "version", "not", "in", "array_rest_versions", ":", "msg", "=", "\"Array is incompatible with REST API version {0}\"", "raise", "ValueError", "(", "msg", ".", "format", "(", "version", ")", ")", "return", "LooseVersion", "(", "version", ")" ]
Validate a REST API version is supported by the library and target array.
[ "Validate", "a", "REST", "API", "version", "is", "supported", "by", "the", "library", "and", "target", "array", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L202-L215
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray._choose_rest_version
def _choose_rest_version(self): """Return the newest REST API version supported by target array.""" versions = self._list_available_rest_versions() versions = [LooseVersion(x) for x in versions if x in self.supported_rest_versions] if versions: return max(versions) else: raise PureError( "Library is incompatible with all REST API versions supported" "by the target array.")
python
def _choose_rest_version(self): """Return the newest REST API version supported by target array.""" versions = self._list_available_rest_versions() versions = [LooseVersion(x) for x in versions if x in self.supported_rest_versions] if versions: return max(versions) else: raise PureError( "Library is incompatible with all REST API versions supported" "by the target array.")
[ "def", "_choose_rest_version", "(", "self", ")", ":", "versions", "=", "self", ".", "_list_available_rest_versions", "(", ")", "versions", "=", "[", "LooseVersion", "(", "x", ")", "for", "x", "in", "versions", "if", "x", "in", "self", ".", "supported_rest_versions", "]", "if", "versions", ":", "return", "max", "(", "versions", ")", "else", ":", "raise", "PureError", "(", "\"Library is incompatible with all REST API versions supported\"", "\"by the target array.\"", ")" ]
Return the newest REST API version supported by target array.
[ "Return", "the", "newest", "REST", "API", "version", "supported", "by", "target", "array", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L217-L226
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray._list_available_rest_versions
def _list_available_rest_versions(self): """Return a list of the REST API versions supported by the array""" url = "https://{0}/api/api_version".format(self._target) data = self._request("GET", url, reestablish_session=False) return data["version"]
python
def _list_available_rest_versions(self): """Return a list of the REST API versions supported by the array""" url = "https://{0}/api/api_version".format(self._target) data = self._request("GET", url, reestablish_session=False) return data["version"]
[ "def", "_list_available_rest_versions", "(", "self", ")", ":", "url", "=", "\"https://{0}/api/api_version\"", ".", "format", "(", "self", ".", "_target", ")", "data", "=", "self", ".", "_request", "(", "\"GET\"", ",", "url", ",", "reestablish_session", "=", "False", ")", "return", "data", "[", "\"version\"", "]" ]
Return a list of the REST API versions supported by the array
[ "Return", "a", "list", "of", "the", "REST", "API", "versions", "supported", "by", "the", "array" ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L228-L233
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray._obtain_api_token
def _obtain_api_token(self, username, password): """Use username and password to obtain and return an API token.""" data = self._request("POST", "auth/apitoken", {"username": username, "password": password}, reestablish_session=False) return data["api_token"]
python
def _obtain_api_token(self, username, password): """Use username and password to obtain and return an API token.""" data = self._request("POST", "auth/apitoken", {"username": username, "password": password}, reestablish_session=False) return data["api_token"]
[ "def", "_obtain_api_token", "(", "self", ",", "username", ",", "password", ")", ":", "data", "=", "self", ".", "_request", "(", "\"POST\"", ",", "\"auth/apitoken\"", ",", "{", "\"username\"", ":", "username", ",", "\"password\"", ":", "password", "}", ",", "reestablish_session", "=", "False", ")", "return", "data", "[", "\"api_token\"", "]" ]
Use username and password to obtain and return an API token.
[ "Use", "username", "and", "password", "to", "obtain", "and", "return", "an", "API", "token", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L235-L240
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.create_snapshots
def create_snapshots(self, volumes, **kwargs): """Create snapshots of the listed volumes. :param volumes: List of names of the volumes to snapshot. :type volumes: list of str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST volume** :type \*\*kwargs: optional :returns: A list of dictionaries describing the new snapshots. :rtype: ResponseDict """ data = {"source": volumes, "snap": True} data.update(kwargs) return self._request("POST", "volume", data)
python
def create_snapshots(self, volumes, **kwargs): """Create snapshots of the listed volumes. :param volumes: List of names of the volumes to snapshot. :type volumes: list of str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST volume** :type \*\*kwargs: optional :returns: A list of dictionaries describing the new snapshots. :rtype: ResponseDict """ data = {"source": volumes, "snap": True} data.update(kwargs) return self._request("POST", "volume", data)
[ "def", "create_snapshots", "(", "self", ",", "volumes", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "\"source\"", ":", "volumes", ",", "\"snap\"", ":", "True", "}", "data", ".", "update", "(", "kwargs", ")", "return", "self", ".", "_request", "(", "\"POST\"", ",", "\"volume\"", ",", "data", ")" ]
Create snapshots of the listed volumes. :param volumes: List of names of the volumes to snapshot. :type volumes: list of str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST volume** :type \*\*kwargs: optional :returns: A list of dictionaries describing the new snapshots. :rtype: ResponseDict
[ "Create", "snapshots", "of", "the", "listed", "volumes", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L381-L397
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.create_volume
def create_volume(self, volume, size, **kwargs): """Create a volume and return a dictionary describing it. :param volume: Name of the volume to be created. :type volume: str :param size: Size in bytes, or string representing the size of the volume to be created. :type size: int or str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST volume/:volume** :type \*\*kwargs: optional :returns: A dictionary describing the created volume. :rtype: ResponseDict .. note:: The maximum volume size supported is 4 petabytes (4 * 2^50). .. note:: If size is an int, it must be a multiple of 512. .. note:: If size is a string, it must consist of an integer followed by a valid suffix. Accepted Suffixes ====== ======== ====== Suffix Size Bytes ====== ======== ====== S Sector (2^9) K Kilobyte (2^10) M Megabyte (2^20) G Gigabyte (2^30) T Terabyte (2^40) P Petabyte (2^50) ====== ======== ====== """ data = {"size": size} data.update(kwargs) return self._request("POST", "volume/{0}".format(volume), data)
python
def create_volume(self, volume, size, **kwargs): """Create a volume and return a dictionary describing it. :param volume: Name of the volume to be created. :type volume: str :param size: Size in bytes, or string representing the size of the volume to be created. :type size: int or str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST volume/:volume** :type \*\*kwargs: optional :returns: A dictionary describing the created volume. :rtype: ResponseDict .. note:: The maximum volume size supported is 4 petabytes (4 * 2^50). .. note:: If size is an int, it must be a multiple of 512. .. note:: If size is a string, it must consist of an integer followed by a valid suffix. Accepted Suffixes ====== ======== ====== Suffix Size Bytes ====== ======== ====== S Sector (2^9) K Kilobyte (2^10) M Megabyte (2^20) G Gigabyte (2^30) T Terabyte (2^40) P Petabyte (2^50) ====== ======== ====== """ data = {"size": size} data.update(kwargs) return self._request("POST", "volume/{0}".format(volume), data)
[ "def", "create_volume", "(", "self", ",", "volume", ",", "size", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "\"size\"", ":", "size", "}", "data", ".", "update", "(", "kwargs", ")", "return", "self", ".", "_request", "(", "\"POST\"", ",", "\"volume/{0}\"", ".", "format", "(", "volume", ")", ",", "data", ")" ]
Create a volume and return a dictionary describing it. :param volume: Name of the volume to be created. :type volume: str :param size: Size in bytes, or string representing the size of the volume to be created. :type size: int or str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST volume/:volume** :type \*\*kwargs: optional :returns: A dictionary describing the created volume. :rtype: ResponseDict .. note:: The maximum volume size supported is 4 petabytes (4 * 2^50). .. note:: If size is an int, it must be a multiple of 512. .. note:: If size is a string, it must consist of an integer followed by a valid suffix. Accepted Suffixes ====== ======== ====== Suffix Size Bytes ====== ======== ====== S Sector (2^9) K Kilobyte (2^10) M Megabyte (2^20) G Gigabyte (2^30) T Terabyte (2^40) P Petabyte (2^50) ====== ======== ======
[ "Create", "a", "volume", "and", "return", "a", "dictionary", "describing", "it", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L399-L444
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.extend_volume
def extend_volume(self, volume, size): """Extend a volume to a new, larger size. :param volume: Name of the volume to be extended. :type volume: str :type size: int or str :param size: Size in bytes, or string representing the size of the volume to be created. :returns: A dictionary mapping "name" to volume and "size" to the volume's new size in bytes. :rtype: ResponseDict .. note:: The new size must be larger than the volume's old size. .. note:: The maximum volume size supported is 4 petabytes (4 * 2^50). .. note:: If size is an int, it must be a multiple of 512. .. note:: If size is a string, it must consist of an integer followed by a valid suffix. Accepted Suffixes ====== ======== ====== Suffix Size Bytes ====== ======== ====== S Sector (2^9) K Kilobyte (2^10) M Megabyte (2^20) G Gigabyte (2^30) T Terabyte (2^40) P Petabyte (2^50) ====== ======== ====== """ return self.set_volume(volume, size=size, truncate=False)
python
def extend_volume(self, volume, size): """Extend a volume to a new, larger size. :param volume: Name of the volume to be extended. :type volume: str :type size: int or str :param size: Size in bytes, or string representing the size of the volume to be created. :returns: A dictionary mapping "name" to volume and "size" to the volume's new size in bytes. :rtype: ResponseDict .. note:: The new size must be larger than the volume's old size. .. note:: The maximum volume size supported is 4 petabytes (4 * 2^50). .. note:: If size is an int, it must be a multiple of 512. .. note:: If size is a string, it must consist of an integer followed by a valid suffix. Accepted Suffixes ====== ======== ====== Suffix Size Bytes ====== ======== ====== S Sector (2^9) K Kilobyte (2^10) M Megabyte (2^20) G Gigabyte (2^30) T Terabyte (2^40) P Petabyte (2^50) ====== ======== ====== """ return self.set_volume(volume, size=size, truncate=False)
[ "def", "extend_volume", "(", "self", ",", "volume", ",", "size", ")", ":", "return", "self", ".", "set_volume", "(", "volume", ",", "size", "=", "size", ",", "truncate", "=", "False", ")" ]
Extend a volume to a new, larger size. :param volume: Name of the volume to be extended. :type volume: str :type size: int or str :param size: Size in bytes, or string representing the size of the volume to be created. :returns: A dictionary mapping "name" to volume and "size" to the volume's new size in bytes. :rtype: ResponseDict .. note:: The new size must be larger than the volume's old size. .. note:: The maximum volume size supported is 4 petabytes (4 * 2^50). .. note:: If size is an int, it must be a multiple of 512. .. note:: If size is a string, it must consist of an integer followed by a valid suffix. Accepted Suffixes ====== ======== ====== Suffix Size Bytes ====== ======== ====== S Sector (2^9) K Kilobyte (2^10) M Megabyte (2^20) G Gigabyte (2^30) T Terabyte (2^40) P Petabyte (2^50) ====== ======== ======
[ "Extend", "a", "volume", "to", "a", "new", "larger", "size", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L529-L573
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.truncate_volume
def truncate_volume(self, volume, size): """Truncate a volume to a new, smaller size. :param volume: Name of the volume to truncate. :type volume: str :param size: Size in bytes, or string representing the size of the volume to be created. :type size: int or str :returns: A dictionary mapping "name" to volume and "size" to the volume's new size in bytes. :rtype: ResponseDict .. warnings also:: Data may be irretrievably lost in this operation. .. note:: A snapshot of the volume in its previous state is taken and immediately destroyed, but it is available for recovery for the 24 hours following the truncation. """ return self.set_volume(volume, size=size, truncate=True)
python
def truncate_volume(self, volume, size): """Truncate a volume to a new, smaller size. :param volume: Name of the volume to truncate. :type volume: str :param size: Size in bytes, or string representing the size of the volume to be created. :type size: int or str :returns: A dictionary mapping "name" to volume and "size" to the volume's new size in bytes. :rtype: ResponseDict .. warnings also:: Data may be irretrievably lost in this operation. .. note:: A snapshot of the volume in its previous state is taken and immediately destroyed, but it is available for recovery for the 24 hours following the truncation. """ return self.set_volume(volume, size=size, truncate=True)
[ "def", "truncate_volume", "(", "self", ",", "volume", ",", "size", ")", ":", "return", "self", ".", "set_volume", "(", "volume", ",", "size", "=", "size", ",", "truncate", "=", "True", ")" ]
Truncate a volume to a new, smaller size. :param volume: Name of the volume to truncate. :type volume: str :param size: Size in bytes, or string representing the size of the volume to be created. :type size: int or str :returns: A dictionary mapping "name" to volume and "size" to the volume's new size in bytes. :rtype: ResponseDict .. warnings also:: Data may be irretrievably lost in this operation. .. note:: A snapshot of the volume in its previous state is taken and immediately destroyed, but it is available for recovery for the 24 hours following the truncation.
[ "Truncate", "a", "volume", "to", "a", "new", "smaller", "size", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L726-L750
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.connect_host
def connect_host(self, host, volume, **kwargs): """Create a connection between a host and a volume. :param host: Name of host to connect to volume. :type host: str :param volume: Name of volume to connect to host. :type volume: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST host/:host/volume/:volume** :type \*\*kwargs: optional :returns: A dictionary describing the connection between the host and volume. :rtype: ResponseDict """ return self._request( "POST", "host/{0}/volume/{1}".format(host, volume), kwargs)
python
def connect_host(self, host, volume, **kwargs): """Create a connection between a host and a volume. :param host: Name of host to connect to volume. :type host: str :param volume: Name of volume to connect to host. :type volume: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST host/:host/volume/:volume** :type \*\*kwargs: optional :returns: A dictionary describing the connection between the host and volume. :rtype: ResponseDict """ return self._request( "POST", "host/{0}/volume/{1}".format(host, volume), kwargs)
[ "def", "connect_host", "(", "self", ",", "host", ",", "volume", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_request", "(", "\"POST\"", ",", "\"host/{0}/volume/{1}\"", ".", "format", "(", "host", ",", "volume", ")", ",", "kwargs", ")" ]
Create a connection between a host and a volume. :param host: Name of host to connect to volume. :type host: str :param volume: Name of volume to connect to host. :type volume: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST host/:host/volume/:volume** :type \*\*kwargs: optional :returns: A dictionary describing the connection between the host and volume. :rtype: ResponseDict
[ "Create", "a", "connection", "between", "a", "host", "and", "a", "volume", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L776-L793
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.connect_hgroup
def connect_hgroup(self, hgroup, volume, **kwargs): """Create a shared connection between a host group and a volume. :param hgroup: Name of hgroup to connect to volume. :type hgroup: str :param volume: Name of volume to connect to hgroup. :type volume: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST hgroup/:hgroup/volume/:volume** :type \*\*kwargs: optional :returns: A dictionary describing the connection between the hgroup and volume. :rtype: ResponseDict """ return self._request( "POST", "hgroup/{0}/volume/{1}".format(hgroup, volume), kwargs)
python
def connect_hgroup(self, hgroup, volume, **kwargs): """Create a shared connection between a host group and a volume. :param hgroup: Name of hgroup to connect to volume. :type hgroup: str :param volume: Name of volume to connect to hgroup. :type volume: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST hgroup/:hgroup/volume/:volume** :type \*\*kwargs: optional :returns: A dictionary describing the connection between the hgroup and volume. :rtype: ResponseDict """ return self._request( "POST", "hgroup/{0}/volume/{1}".format(hgroup, volume), kwargs)
[ "def", "connect_hgroup", "(", "self", ",", "hgroup", ",", "volume", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_request", "(", "\"POST\"", ",", "\"hgroup/{0}/volume/{1}\"", ".", "format", "(", "hgroup", ",", "volume", ")", ",", "kwargs", ")" ]
Create a shared connection between a host group and a volume. :param hgroup: Name of hgroup to connect to volume. :type hgroup: str :param volume: Name of volume to connect to hgroup. :type volume: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST hgroup/:hgroup/volume/:volume** :type \*\*kwargs: optional :returns: A dictionary describing the connection between the hgroup and volume. :rtype: ResponseDict
[ "Create", "a", "shared", "connection", "between", "a", "host", "group", "and", "a", "volume", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L952-L969
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.get_offload
def get_offload(self, name, **kwargs): """Return a dictionary describing the connected offload target. :param offload: Name of offload target to get information about. :type offload: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **GET offload/::offload** :type \*\*kwargs: optional :returns: A dictionary describing the offload connection. :rtype: ResponseDict """ # Unbox if a list to accommodate a bug in REST 1.14 result = self._request("GET", "offload/{0}".format(name), kwargs) if isinstance(result, list): headers = result.headers result = ResponseDict(result[0]) result.headers = headers return result
python
def get_offload(self, name, **kwargs): """Return a dictionary describing the connected offload target. :param offload: Name of offload target to get information about. :type offload: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **GET offload/::offload** :type \*\*kwargs: optional :returns: A dictionary describing the offload connection. :rtype: ResponseDict """ # Unbox if a list to accommodate a bug in REST 1.14 result = self._request("GET", "offload/{0}".format(name), kwargs) if isinstance(result, list): headers = result.headers result = ResponseDict(result[0]) result.headers = headers return result
[ "def", "get_offload", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "# Unbox if a list to accommodate a bug in REST 1.14", "result", "=", "self", ".", "_request", "(", "\"GET\"", ",", "\"offload/{0}\"", ".", "format", "(", "name", ")", ",", "kwargs", ")", "if", "isinstance", "(", "result", ",", "list", ")", ":", "headers", "=", "result", ".", "headers", "result", "=", "ResponseDict", "(", "result", "[", "0", "]", ")", "result", ".", "headers", "=", "headers", "return", "result" ]
Return a dictionary describing the connected offload target. :param offload: Name of offload target to get information about. :type offload: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **GET offload/::offload** :type \*\*kwargs: optional :returns: A dictionary describing the offload connection. :rtype: ResponseDict
[ "Return", "a", "dictionary", "describing", "the", "connected", "offload", "target", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L1222-L1242
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.create_subnet
def create_subnet(self, subnet, prefix, **kwargs): """Create a subnet. :param subnet: Name of subnet to be created. :type subnet: str :param prefix: Routing prefix of subnet to be created. :type prefix: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST subnet/:subnet** :type \*\*kwargs: optional :returns: A dictionary describing the created subnet. :rtype: ResponseDict .. note:: prefix should be specified as an IPv4 CIDR address. ("xxx.xxx.xxx.xxx/nn", representing prefix and prefix length) .. note:: Requires use of REST API 1.5 or later. """ data = {"prefix": prefix} data.update(kwargs) return self._request("POST", "subnet/{0}".format(subnet), data)
python
def create_subnet(self, subnet, prefix, **kwargs): """Create a subnet. :param subnet: Name of subnet to be created. :type subnet: str :param prefix: Routing prefix of subnet to be created. :type prefix: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST subnet/:subnet** :type \*\*kwargs: optional :returns: A dictionary describing the created subnet. :rtype: ResponseDict .. note:: prefix should be specified as an IPv4 CIDR address. ("xxx.xxx.xxx.xxx/nn", representing prefix and prefix length) .. note:: Requires use of REST API 1.5 or later. """ data = {"prefix": prefix} data.update(kwargs) return self._request("POST", "subnet/{0}".format(subnet), data)
[ "def", "create_subnet", "(", "self", ",", "subnet", ",", "prefix", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "\"prefix\"", ":", "prefix", "}", "data", ".", "update", "(", "kwargs", ")", "return", "self", ".", "_request", "(", "\"POST\"", ",", "\"subnet/{0}\"", ".", "format", "(", "subnet", ")", ",", "data", ")" ]
Create a subnet. :param subnet: Name of subnet to be created. :type subnet: str :param prefix: Routing prefix of subnet to be created. :type prefix: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST subnet/:subnet** :type \*\*kwargs: optional :returns: A dictionary describing the created subnet. :rtype: ResponseDict .. note:: prefix should be specified as an IPv4 CIDR address. ("xxx.xxx.xxx.xxx/nn", representing prefix and prefix length) .. note:: Requires use of REST API 1.5 or later.
[ "Create", "a", "subnet", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L1347-L1374
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.create_vlan_interface
def create_vlan_interface(self, interface, subnet, **kwargs): """Create a vlan interface :param interface: Name of interface to be created. :type interface: str :param subnet: Subnet associated with interface to be created :type subnet: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST network/vif/:vlan_interface** :type \*\*kwargs: optional :returns: A dictionary describing the created interface :rtype: ResponseDict .. note:: Requires use of REST API 1.5 or later. """ data = {"subnet": subnet} data.update(kwargs) return self._request("POST", "network/vif/{0}".format(interface), data)
python
def create_vlan_interface(self, interface, subnet, **kwargs): """Create a vlan interface :param interface: Name of interface to be created. :type interface: str :param subnet: Subnet associated with interface to be created :type subnet: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST network/vif/:vlan_interface** :type \*\*kwargs: optional :returns: A dictionary describing the created interface :rtype: ResponseDict .. note:: Requires use of REST API 1.5 or later. """ data = {"subnet": subnet} data.update(kwargs) return self._request("POST", "network/vif/{0}".format(interface), data)
[ "def", "create_vlan_interface", "(", "self", ",", "interface", ",", "subnet", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "\"subnet\"", ":", "subnet", "}", "data", ".", "update", "(", "kwargs", ")", "return", "self", ".", "_request", "(", "\"POST\"", ",", "\"network/vif/{0}\"", ".", "format", "(", "interface", ")", ",", "data", ")" ]
Create a vlan interface :param interface: Name of interface to be created. :type interface: str :param subnet: Subnet associated with interface to be created :type subnet: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST network/vif/:vlan_interface** :type \*\*kwargs: optional :returns: A dictionary describing the created interface :rtype: ResponseDict .. note:: Requires use of REST API 1.5 or later.
[ "Create", "a", "vlan", "interface" ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L1496-L1518
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.set_password
def set_password(self, admin, new_password, old_password): """Set an admin's password. :param admin: Name of admin whose password is to be set. :type admin: str :param new_password: New password for admin. :type new_password: str :param old_password: Current password of admin. :type old_password: str :returns: A dictionary mapping "name" to admin. :rtype: ResponseDict """ return self.set_admin(admin, password=new_password, old_password=old_password)
python
def set_password(self, admin, new_password, old_password): """Set an admin's password. :param admin: Name of admin whose password is to be set. :type admin: str :param new_password: New password for admin. :type new_password: str :param old_password: Current password of admin. :type old_password: str :returns: A dictionary mapping "name" to admin. :rtype: ResponseDict """ return self.set_admin(admin, password=new_password, old_password=old_password)
[ "def", "set_password", "(", "self", ",", "admin", ",", "new_password", ",", "old_password", ")", ":", "return", "self", ".", "set_admin", "(", "admin", ",", "password", "=", "new_password", ",", "old_password", "=", "old_password", ")" ]
Set an admin's password. :param admin: Name of admin whose password is to be set. :type admin: str :param new_password: New password for admin. :type new_password: str :param old_password: Current password of admin. :type old_password: str :returns: A dictionary mapping "name" to admin. :rtype: ResponseDict
[ "Set", "an", "admin", "s", "password", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L1888-L1903
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.disable_directory_service
def disable_directory_service(self, check_peer=False): """Disable the directory service. :param check_peer: If True, disables server authenticity enforcement. If False, disables directory service integration. :type check_peer: bool, optional :returns: A dictionary describing the status of the directory service. :rtype: ResponseDict """ if check_peer: return self.set_directory_service(check_peer=False) return self.set_directory_service(enabled=False)
python
def disable_directory_service(self, check_peer=False): """Disable the directory service. :param check_peer: If True, disables server authenticity enforcement. If False, disables directory service integration. :type check_peer: bool, optional :returns: A dictionary describing the status of the directory service. :rtype: ResponseDict """ if check_peer: return self.set_directory_service(check_peer=False) return self.set_directory_service(enabled=False)
[ "def", "disable_directory_service", "(", "self", ",", "check_peer", "=", "False", ")", ":", "if", "check_peer", ":", "return", "self", ".", "set_directory_service", "(", "check_peer", "=", "False", ")", "return", "self", ".", "set_directory_service", "(", "enabled", "=", "False", ")" ]
Disable the directory service. :param check_peer: If True, disables server authenticity enforcement. If False, disables directory service integration. :type check_peer: bool, optional :returns: A dictionary describing the status of the directory service. :rtype: ResponseDict
[ "Disable", "the", "directory", "service", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L1907-L1921
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.enable_directory_service
def enable_directory_service(self, check_peer=False): """Enable the directory service. :param check_peer: If True, enables server authenticity enforcement. If False, enables directory service integration. :type check_peer: bool, optional :returns: A dictionary describing the status of the directory service. :rtype: ResponseDict """ if check_peer: return self.set_directory_service(check_peer=True) return self.set_directory_service(enabled=True)
python
def enable_directory_service(self, check_peer=False): """Enable the directory service. :param check_peer: If True, enables server authenticity enforcement. If False, enables directory service integration. :type check_peer: bool, optional :returns: A dictionary describing the status of the directory service. :rtype: ResponseDict """ if check_peer: return self.set_directory_service(check_peer=True) return self.set_directory_service(enabled=True)
[ "def", "enable_directory_service", "(", "self", ",", "check_peer", "=", "False", ")", ":", "if", "check_peer", ":", "return", "self", ".", "set_directory_service", "(", "check_peer", "=", "True", ")", "return", "self", ".", "set_directory_service", "(", "enabled", "=", "True", ")" ]
Enable the directory service. :param check_peer: If True, enables server authenticity enforcement. If False, enables directory service integration. :type check_peer: bool, optional :returns: A dictionary describing the status of the directory service. :rtype: ResponseDict
[ "Enable", "the", "directory", "service", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L1923-L1937
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.create_snmp_manager
def create_snmp_manager(self, manager, host, **kwargs): """Create an SNMP manager. :param manager: Name of manager to be created. :type manager: str :param host: IP address or DNS name of SNMP server to be used. :type host: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST snmp/:manager** :type \*\*kwargs: optional :returns: A dictionary describing the created SNMP manager. :rtype: ResponseDict """ data = {"host": host} data.update(kwargs) return self._request("POST", "snmp/{0}".format(manager), data)
python
def create_snmp_manager(self, manager, host, **kwargs): """Create an SNMP manager. :param manager: Name of manager to be created. :type manager: str :param host: IP address or DNS name of SNMP server to be used. :type host: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST snmp/:manager** :type \*\*kwargs: optional :returns: A dictionary describing the created SNMP manager. :rtype: ResponseDict """ data = {"host": host} data.update(kwargs) return self._request("POST", "snmp/{0}".format(manager), data)
[ "def", "create_snmp_manager", "(", "self", ",", "manager", ",", "host", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "\"host\"", ":", "host", "}", "data", ".", "update", "(", "kwargs", ")", "return", "self", ".", "_request", "(", "\"POST\"", ",", "\"snmp/{0}\"", ".", "format", "(", "manager", ")", ",", "data", ")" ]
Create an SNMP manager. :param manager: Name of manager to be created. :type manager: str :param host: IP address or DNS name of SNMP server to be used. :type host: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST snmp/:manager** :type \*\*kwargs: optional :returns: A dictionary describing the created SNMP manager. :rtype: ResponseDict
[ "Create", "an", "SNMP", "manager", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L2335-L2353
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.connect_array
def connect_array(self, address, connection_key, connection_type, **kwargs): """Connect this array with another one. :param address: IP address or DNS name of other array. :type address: str :param connection_key: Connection key of other array. :type connection_key: str :param connection_type: Type(s) of connection desired. :type connection_type: list :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST array/connection** :type \*\*kwargs: optional :returns: A dictionary describing the connection to the other array. :rtype: ResponseDict .. note:: Currently, the only type of connection is "replication". .. note:: Requires use of REST API 1.2 or later. """ data = {"management_address": address, "connection_key": connection_key, "type": connection_type} data.update(kwargs) return self._request("POST", "array/connection", data)
python
def connect_array(self, address, connection_key, connection_type, **kwargs): """Connect this array with another one. :param address: IP address or DNS name of other array. :type address: str :param connection_key: Connection key of other array. :type connection_key: str :param connection_type: Type(s) of connection desired. :type connection_type: list :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST array/connection** :type \*\*kwargs: optional :returns: A dictionary describing the connection to the other array. :rtype: ResponseDict .. note:: Currently, the only type of connection is "replication". .. note:: Requires use of REST API 1.2 or later. """ data = {"management_address": address, "connection_key": connection_key, "type": connection_type} data.update(kwargs) return self._request("POST", "array/connection", data)
[ "def", "connect_array", "(", "self", ",", "address", ",", "connection_key", ",", "connection_type", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "\"management_address\"", ":", "address", ",", "\"connection_key\"", ":", "connection_key", ",", "\"type\"", ":", "connection_type", "}", "data", ".", "update", "(", "kwargs", ")", "return", "self", ".", "_request", "(", "\"POST\"", ",", "\"array/connection\"", ",", "data", ")" ]
Connect this array with another one. :param address: IP address or DNS name of other array. :type address: str :param connection_key: Connection key of other array. :type connection_key: str :param connection_type: Type(s) of connection desired. :type connection_type: list :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST array/connection** :type \*\*kwargs: optional :returns: A dictionary describing the connection to the other array. :rtype: ResponseDict .. note:: Currently, the only type of connection is "replication". .. note:: Requires use of REST API 1.2 or later.
[ "Connect", "this", "array", "with", "another", "one", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L2448-L2478
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.create_pgroup_snapshot
def create_pgroup_snapshot(self, source, **kwargs): """Create snapshot of pgroup from specified source. :param source: Name of pgroup of which to take snapshot. :type source: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST pgroup** :type \*\*kwargs: optional :returns: A dictionary describing the created snapshot. :rtype: ResponseDict .. note:: Requires use of REST API 1.2 or later. """ # In REST 1.4, support was added for snapshotting multiple pgroups. As a # result, the endpoint response changed from an object to an array of # objects. To keep the response type consistent between REST versions, # we unbox the response when creating a single snapshot. result = self.create_pgroup_snapshots([source], **kwargs) if self._rest_version >= LooseVersion("1.4"): headers = result.headers result = ResponseDict(result[0]) result.headers = headers return result
python
def create_pgroup_snapshot(self, source, **kwargs): """Create snapshot of pgroup from specified source. :param source: Name of pgroup of which to take snapshot. :type source: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST pgroup** :type \*\*kwargs: optional :returns: A dictionary describing the created snapshot. :rtype: ResponseDict .. note:: Requires use of REST API 1.2 or later. """ # In REST 1.4, support was added for snapshotting multiple pgroups. As a # result, the endpoint response changed from an object to an array of # objects. To keep the response type consistent between REST versions, # we unbox the response when creating a single snapshot. result = self.create_pgroup_snapshots([source], **kwargs) if self._rest_version >= LooseVersion("1.4"): headers = result.headers result = ResponseDict(result[0]) result.headers = headers return result
[ "def", "create_pgroup_snapshot", "(", "self", ",", "source", ",", "*", "*", "kwargs", ")", ":", "# In REST 1.4, support was added for snapshotting multiple pgroups. As a", "# result, the endpoint response changed from an object to an array of", "# objects. To keep the response type consistent between REST versions,", "# we unbox the response when creating a single snapshot.", "result", "=", "self", ".", "create_pgroup_snapshots", "(", "[", "source", "]", ",", "*", "*", "kwargs", ")", "if", "self", ".", "_rest_version", ">=", "LooseVersion", "(", "\"1.4\"", ")", ":", "headers", "=", "result", ".", "headers", "result", "=", "ResponseDict", "(", "result", "[", "0", "]", ")", "result", ".", "headers", "=", "headers", "return", "result" ]
Create snapshot of pgroup from specified source. :param source: Name of pgroup of which to take snapshot. :type source: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST pgroup** :type \*\*kwargs: optional :returns: A dictionary describing the created snapshot. :rtype: ResponseDict .. note:: Requires use of REST API 1.2 or later.
[ "Create", "snapshot", "of", "pgroup", "from", "specified", "source", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L2552-L2579
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.send_pgroup_snapshot
def send_pgroup_snapshot(self, source, **kwargs): """ Send an existing pgroup snapshot to target(s) :param source: Name of pgroup snapshot to send. :type source: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST pgroup** :type \*\*kwargs: optional :returns: A list of dictionaries describing the sent snapshots. :rtype: ResponseList .. note:: Requires use of REST API 1.16 or later. """ data = {"name": [source], "action":"send"} data.update(kwargs) return self._request("POST", "pgroup", data)
python
def send_pgroup_snapshot(self, source, **kwargs): """ Send an existing pgroup snapshot to target(s) :param source: Name of pgroup snapshot to send. :type source: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST pgroup** :type \*\*kwargs: optional :returns: A list of dictionaries describing the sent snapshots. :rtype: ResponseList .. note:: Requires use of REST API 1.16 or later. """ data = {"name": [source], "action":"send"} data.update(kwargs) return self._request("POST", "pgroup", data)
[ "def", "send_pgroup_snapshot", "(", "self", ",", "source", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "\"name\"", ":", "[", "source", "]", ",", "\"action\"", ":", "\"send\"", "}", "data", ".", "update", "(", "kwargs", ")", "return", "self", ".", "_request", "(", "\"POST\"", ",", "\"pgroup\"", ",", "data", ")" ]
Send an existing pgroup snapshot to target(s) :param source: Name of pgroup snapshot to send. :type source: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST pgroup** :type \*\*kwargs: optional :returns: A list of dictionaries describing the sent snapshots. :rtype: ResponseList .. note:: Requires use of REST API 1.16 or later.
[ "Send", "an", "existing", "pgroup", "snapshot", "to", "target", "(", "s", ")" ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L2581-L2601
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.create_pgroup_snapshots
def create_pgroup_snapshots(self, sources, **kwargs): """Create snapshots of pgroups from specified sources. :param sources: Names of pgroups of which to take snapshots. :type sources: list of str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST pgroup** :type \*\*kwargs: optional :returns: A list of dictionaries describing the created snapshots. :rtype: ResponseList .. note:: Requires use of REST API 1.2 or later. """ data = {"source": sources, "snap": True} data.update(kwargs) return self._request("POST", "pgroup", data)
python
def create_pgroup_snapshots(self, sources, **kwargs): """Create snapshots of pgroups from specified sources. :param sources: Names of pgroups of which to take snapshots. :type sources: list of str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST pgroup** :type \*\*kwargs: optional :returns: A list of dictionaries describing the created snapshots. :rtype: ResponseList .. note:: Requires use of REST API 1.2 or later. """ data = {"source": sources, "snap": True} data.update(kwargs) return self._request("POST", "pgroup", data)
[ "def", "create_pgroup_snapshots", "(", "self", ",", "sources", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "\"source\"", ":", "sources", ",", "\"snap\"", ":", "True", "}", "data", ".", "update", "(", "kwargs", ")", "return", "self", ".", "_request", "(", "\"POST\"", ",", "\"pgroup\"", ",", "data", ")" ]
Create snapshots of pgroups from specified sources. :param sources: Names of pgroups of which to take snapshots. :type sources: list of str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST pgroup** :type \*\*kwargs: optional :returns: A list of dictionaries describing the created snapshots. :rtype: ResponseList .. note:: Requires use of REST API 1.2 or later.
[ "Create", "snapshots", "of", "pgroups", "from", "specified", "sources", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L2603-L2623
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.eradicate_pgroup
def eradicate_pgroup(self, pgroup, **kwargs): """Eradicate a destroyed pgroup. :param pgroup: Name of pgroup to be eradicated. :type pgroup: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **DELETE pgroup/:pgroup** :type \*\*kwargs: optional :returns: A dictionary mapping "name" to pgroup. :rtype: ResponseDict .. note:: Requires use of REST API 1.2 or later. """ eradicate = {"eradicate": True} eradicate.update(kwargs) return self._request("DELETE", "pgroup/{0}".format(pgroup), eradicate)
python
def eradicate_pgroup(self, pgroup, **kwargs): """Eradicate a destroyed pgroup. :param pgroup: Name of pgroup to be eradicated. :type pgroup: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **DELETE pgroup/:pgroup** :type \*\*kwargs: optional :returns: A dictionary mapping "name" to pgroup. :rtype: ResponseDict .. note:: Requires use of REST API 1.2 or later. """ eradicate = {"eradicate": True} eradicate.update(kwargs) return self._request("DELETE", "pgroup/{0}".format(pgroup), eradicate)
[ "def", "eradicate_pgroup", "(", "self", ",", "pgroup", ",", "*", "*", "kwargs", ")", ":", "eradicate", "=", "{", "\"eradicate\"", ":", "True", "}", "eradicate", ".", "update", "(", "kwargs", ")", "return", "self", ".", "_request", "(", "\"DELETE\"", ",", "\"pgroup/{0}\"", ".", "format", "(", "pgroup", ")", ",", "eradicate", ")" ]
Eradicate a destroyed pgroup. :param pgroup: Name of pgroup to be eradicated. :type pgroup: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **DELETE pgroup/:pgroup** :type \*\*kwargs: optional :returns: A dictionary mapping "name" to pgroup. :rtype: ResponseDict .. note:: Requires use of REST API 1.2 or later.
[ "Eradicate", "a", "destroyed", "pgroup", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L2708-L2728
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.clone_pod
def clone_pod(self, source, dest, **kwargs): """Clone an existing pod to a new one. :param source: Name of the pod the be cloned. :type source: str :param dest: Name of the target pod to clone into :type dest: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST pod/:pod** :type \*\*kwargs: optional :returns: A dictionary describing the created pod :rtype: ResponseDict .. note:: Requires use of REST API 1.13 or later. """ data = {"source": source} data.update(kwargs) return self._request("POST", "pod/{0}".format(dest), data)
python
def clone_pod(self, source, dest, **kwargs): """Clone an existing pod to a new one. :param source: Name of the pod the be cloned. :type source: str :param dest: Name of the target pod to clone into :type dest: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST pod/:pod** :type \*\*kwargs: optional :returns: A dictionary describing the created pod :rtype: ResponseDict .. note:: Requires use of REST API 1.13 or later. """ data = {"source": source} data.update(kwargs) return self._request("POST", "pod/{0}".format(dest), data)
[ "def", "clone_pod", "(", "self", ",", "source", ",", "dest", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "\"source\"", ":", "source", "}", "data", ".", "update", "(", "kwargs", ")", "return", "self", ".", "_request", "(", "\"POST\"", ",", "\"pod/{0}\"", ".", "format", "(", "dest", ")", ",", "data", ")" ]
Clone an existing pod to a new one. :param source: Name of the pod the be cloned. :type source: str :param dest: Name of the target pod to clone into :type dest: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **POST pod/:pod** :type \*\*kwargs: optional :returns: A dictionary describing the created pod :rtype: ResponseDict .. note:: Requires use of REST API 1.13 or later.
[ "Clone", "an", "existing", "pod", "to", "a", "new", "one", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L3017-L3038
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.remove_pod
def remove_pod(self, pod, array, **kwargs): """Remove arrays from a pod. :param pod: Name of the pod. :type pod: str :param array: Array to remove from pod. :type array: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **DELETE pod/:pod**/array/:array** :type \*\*kwargs: optional :returns: A dictionary mapping "name" to pod and "array" to the pod's new array list. :rtype: ResponseDict .. note:: Requires use of REST API 1.13 or later. """ return self._request("DELETE", "pod/{0}/array/{1}".format(pod, array), kwargs)
python
def remove_pod(self, pod, array, **kwargs): """Remove arrays from a pod. :param pod: Name of the pod. :type pod: str :param array: Array to remove from pod. :type array: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **DELETE pod/:pod**/array/:array** :type \*\*kwargs: optional :returns: A dictionary mapping "name" to pod and "array" to the pod's new array list. :rtype: ResponseDict .. note:: Requires use of REST API 1.13 or later. """ return self._request("DELETE", "pod/{0}/array/{1}".format(pod, array), kwargs)
[ "def", "remove_pod", "(", "self", ",", "pod", ",", "array", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_request", "(", "\"DELETE\"", ",", "\"pod/{0}/array/{1}\"", ".", "format", "(", "pod", ",", "array", ")", ",", "kwargs", ")" ]
Remove arrays from a pod. :param pod: Name of the pod. :type pod: str :param array: Array to remove from pod. :type array: str :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **DELETE pod/:pod**/array/:array** :type \*\*kwargs: optional :returns: A dictionary mapping "name" to pod and "array" to the pod's new array list. :rtype: ResponseDict .. note:: Requires use of REST API 1.13 or later.
[ "Remove", "arrays", "from", "a", "pod", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L3125-L3144
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.get_certificate
def get_certificate(self, **kwargs): """Get the attributes of the current array certificate. :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **GET cert** :type \*\*kwargs: optional :returns: A dictionary describing the configured array certificate. :rtype: ResponseDict .. note:: Requires use of REST API 1.3 or later. """ if self._rest_version >= LooseVersion("1.12"): return self._request("GET", "cert/{0}".format(kwargs.pop('name', 'management')), kwargs) else: return self._request("GET", "cert", kwargs)
python
def get_certificate(self, **kwargs): """Get the attributes of the current array certificate. :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **GET cert** :type \*\*kwargs: optional :returns: A dictionary describing the configured array certificate. :rtype: ResponseDict .. note:: Requires use of REST API 1.3 or later. """ if self._rest_version >= LooseVersion("1.12"): return self._request("GET", "cert/{0}".format(kwargs.pop('name', 'management')), kwargs) else: return self._request("GET", "cert", kwargs)
[ "def", "get_certificate", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_rest_version", ">=", "LooseVersion", "(", "\"1.12\"", ")", ":", "return", "self", ".", "_request", "(", "\"GET\"", ",", "\"cert/{0}\"", ".", "format", "(", "kwargs", ".", "pop", "(", "'name'", ",", "'management'", ")", ")", ",", "kwargs", ")", "else", ":", "return", "self", ".", "_request", "(", "\"GET\"", ",", "\"cert\"", ",", "kwargs", ")" ]
Get the attributes of the current array certificate. :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **GET cert** :type \*\*kwargs: optional :returns: A dictionary describing the configured array certificate. :rtype: ResponseDict .. note:: Requires use of REST API 1.3 or later.
[ "Get", "the", "attributes", "of", "the", "current", "array", "certificate", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L3211-L3232
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.list_certificates
def list_certificates(self): """Get the attributes of the current array certificate. :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **GET cert** :type \*\*kwargs: optional :returns: A list of dictionaries describing all configured certificates. :rtype: ResponseList .. note:: Requires use of REST API 1.12 or later. """ # This call takes no parameters. if self._rest_version >= LooseVersion("1.12"): return self._request("GET", "cert") else: # If someone tries to call this against a too-early api version, # do the best we can to provide expected behavior. cert = self._request("GET", "cert") out = ResponseList([cert]) out.headers = cert.headers return out
python
def list_certificates(self): """Get the attributes of the current array certificate. :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **GET cert** :type \*\*kwargs: optional :returns: A list of dictionaries describing all configured certificates. :rtype: ResponseList .. note:: Requires use of REST API 1.12 or later. """ # This call takes no parameters. if self._rest_version >= LooseVersion("1.12"): return self._request("GET", "cert") else: # If someone tries to call this against a too-early api version, # do the best we can to provide expected behavior. cert = self._request("GET", "cert") out = ResponseList([cert]) out.headers = cert.headers return out
[ "def", "list_certificates", "(", "self", ")", ":", "# This call takes no parameters.", "if", "self", ".", "_rest_version", ">=", "LooseVersion", "(", "\"1.12\"", ")", ":", "return", "self", ".", "_request", "(", "\"GET\"", ",", "\"cert\"", ")", "else", ":", "# If someone tries to call this against a too-early api version,", "# do the best we can to provide expected behavior.", "cert", "=", "self", ".", "_request", "(", "\"GET\"", ",", "\"cert\"", ")", "out", "=", "ResponseList", "(", "[", "cert", "]", ")", "out", ".", "headers", "=", "cert", ".", "headers", "return", "out" ]
Get the attributes of the current array certificate. :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **GET cert** :type \*\*kwargs: optional :returns: A list of dictionaries describing all configured certificates. :rtype: ResponseList .. note:: Requires use of REST API 1.12 or later.
[ "Get", "the", "attributes", "of", "the", "current", "array", "certificate", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L3234-L3260
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.get_certificate_signing_request
def get_certificate_signing_request(self, **kwargs): """Construct a certificate signing request (CSR) for signing by a certificate authority (CA). :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **GET cert/certificate_signing_request** :type \*\*kwargs: optional :returns: A dictionary mapping "certificate_signing_request" to the CSR. :rtype: ResponseDict .. note:: Requires use of REST API 1.3 or later. In version 1.12, purecert was expanded to allow manipulation of multiple certificates, by name. To preserve backwards compatibility, the default name, if none is specified, for this version is 'management' which acts on the certificate previously managed by this command. """ if self._rest_version >= LooseVersion("1.12"): return self._request("GET", "cert/certificate_signing_request/{0}".format( kwargs.pop('name', 'management')), kwargs) else: return self._request("GET", "cert/certificate_signing_request", kwargs)
python
def get_certificate_signing_request(self, **kwargs): """Construct a certificate signing request (CSR) for signing by a certificate authority (CA). :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **GET cert/certificate_signing_request** :type \*\*kwargs: optional :returns: A dictionary mapping "certificate_signing_request" to the CSR. :rtype: ResponseDict .. note:: Requires use of REST API 1.3 or later. In version 1.12, purecert was expanded to allow manipulation of multiple certificates, by name. To preserve backwards compatibility, the default name, if none is specified, for this version is 'management' which acts on the certificate previously managed by this command. """ if self._rest_version >= LooseVersion("1.12"): return self._request("GET", "cert/certificate_signing_request/{0}".format( kwargs.pop('name', 'management')), kwargs) else: return self._request("GET", "cert/certificate_signing_request", kwargs)
[ "def", "get_certificate_signing_request", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_rest_version", ">=", "LooseVersion", "(", "\"1.12\"", ")", ":", "return", "self", ".", "_request", "(", "\"GET\"", ",", "\"cert/certificate_signing_request/{0}\"", ".", "format", "(", "kwargs", ".", "pop", "(", "'name'", ",", "'management'", ")", ")", ",", "kwargs", ")", "else", ":", "return", "self", ".", "_request", "(", "\"GET\"", ",", "\"cert/certificate_signing_request\"", ",", "kwargs", ")" ]
Construct a certificate signing request (CSR) for signing by a certificate authority (CA). :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **GET cert/certificate_signing_request** :type \*\*kwargs: optional :returns: A dictionary mapping "certificate_signing_request" to the CSR. :rtype: ResponseDict .. note:: Requires use of REST API 1.3 or later. In version 1.12, purecert was expanded to allow manipulation of multiple certificates, by name. To preserve backwards compatibility, the default name, if none is specified, for this version is 'management' which acts on the certificate previously managed by this command.
[ "Construct", "a", "certificate", "signing", "request", "(", "CSR", ")", "for", "signing", "by", "a", "certificate", "authority", "(", "CA", ")", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L3262-L3289
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.set_certificate
def set_certificate(self, **kwargs): """Modify an existing certificate, creating a new self signed one or importing a certificate signed by a certificate authority (CA). :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **PUT cert** :type \*\*kwargs: optional :returns: A dictionary describing the configured array certificate. :rtype: ResponseDict .. note:: Requires use of REST API 1.3 or later. In version 1.12, purecert was expanded to allow manipulation of multiple certificates, by name. To preserve backwards compatibility, the default name, if none is specified, for this version is 'management' which acts on the certificate previously managed by this command. """ if self._rest_version >= LooseVersion("1.12"): return self._request("PUT", "cert/{0}".format(kwargs.pop('name', 'management')), kwargs) else: return self._request("PUT", "cert", kwargs)
python
def set_certificate(self, **kwargs): """Modify an existing certificate, creating a new self signed one or importing a certificate signed by a certificate authority (CA). :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **PUT cert** :type \*\*kwargs: optional :returns: A dictionary describing the configured array certificate. :rtype: ResponseDict .. note:: Requires use of REST API 1.3 or later. In version 1.12, purecert was expanded to allow manipulation of multiple certificates, by name. To preserve backwards compatibility, the default name, if none is specified, for this version is 'management' which acts on the certificate previously managed by this command. """ if self._rest_version >= LooseVersion("1.12"): return self._request("PUT", "cert/{0}".format(kwargs.pop('name', 'management')), kwargs) else: return self._request("PUT", "cert", kwargs)
[ "def", "set_certificate", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_rest_version", ">=", "LooseVersion", "(", "\"1.12\"", ")", ":", "return", "self", ".", "_request", "(", "\"PUT\"", ",", "\"cert/{0}\"", ".", "format", "(", "kwargs", ".", "pop", "(", "'name'", ",", "'management'", ")", ")", ",", "kwargs", ")", "else", ":", "return", "self", ".", "_request", "(", "\"PUT\"", ",", "\"cert\"", ",", "kwargs", ")" ]
Modify an existing certificate, creating a new self signed one or importing a certificate signed by a certificate authority (CA). :param \*\*kwargs: See the REST API Guide on your array for the documentation on the request: **PUT cert** :type \*\*kwargs: optional :returns: A dictionary describing the configured array certificate. :rtype: ResponseDict .. note:: Requires use of REST API 1.3 or later. In version 1.12, purecert was expanded to allow manipulation of multiple certificates, by name. To preserve backwards compatibility, the default name, if none is specified, for this version is 'management' which acts on the certificate previously managed by this command.
[ "Modify", "an", "existing", "certificate", "creating", "a", "new", "self", "signed", "one", "or", "importing", "a", "certificate", "signed", "by", "a", "certificate", "authority", "(", "CA", ")", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L3291-L3317
train
PureStorage-OpenConnect/rest-client
purestorage/purestorage.py
FlashArray.page_through
def page_through(page_size, function, *args, **kwargs): """Return an iterator over all pages of a REST operation. :param page_size: Number of elements to retrieve per call. :param function: FlashArray function that accepts limit as an argument. :param \*args: Positional arguments to be passed to function. :param \*\*kwargs: Keyword arguments to be passed to function. :returns: An iterator of tuples containing a page of results for the function(\*args, \*\*kwargs) and None, or None and a PureError if a call to retrieve a page fails. :rtype: iterator .. note:: Requires use of REST API 1.7 or later. Only works with functions that accept limit as an argument. Iterator will retrieve page_size elements per call Iterator will yield None and an error if a call fails. The next call will repeat the same call, unless the caller sends in an alternate page token. """ kwargs["limit"] = page_size def get_page(token): page_kwargs = kwargs.copy() if token: page_kwargs["token"] = token return function(*args, **page_kwargs) def page_generator(): token = None while True: try: response = get_page(token) token = response.headers.get("x-next-token") except PureError as err: yield None, err else: if response: sent_token = yield response, None if sent_token is not None: token = sent_token else: return return page_generator()
python
def page_through(page_size, function, *args, **kwargs): """Return an iterator over all pages of a REST operation. :param page_size: Number of elements to retrieve per call. :param function: FlashArray function that accepts limit as an argument. :param \*args: Positional arguments to be passed to function. :param \*\*kwargs: Keyword arguments to be passed to function. :returns: An iterator of tuples containing a page of results for the function(\*args, \*\*kwargs) and None, or None and a PureError if a call to retrieve a page fails. :rtype: iterator .. note:: Requires use of REST API 1.7 or later. Only works with functions that accept limit as an argument. Iterator will retrieve page_size elements per call Iterator will yield None and an error if a call fails. The next call will repeat the same call, unless the caller sends in an alternate page token. """ kwargs["limit"] = page_size def get_page(token): page_kwargs = kwargs.copy() if token: page_kwargs["token"] = token return function(*args, **page_kwargs) def page_generator(): token = None while True: try: response = get_page(token) token = response.headers.get("x-next-token") except PureError as err: yield None, err else: if response: sent_token = yield response, None if sent_token is not None: token = sent_token else: return return page_generator()
[ "def", "page_through", "(", "page_size", ",", "function", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"limit\"", "]", "=", "page_size", "def", "get_page", "(", "token", ")", ":", "page_kwargs", "=", "kwargs", ".", "copy", "(", ")", "if", "token", ":", "page_kwargs", "[", "\"token\"", "]", "=", "token", "return", "function", "(", "*", "args", ",", "*", "*", "page_kwargs", ")", "def", "page_generator", "(", ")", ":", "token", "=", "None", "while", "True", ":", "try", ":", "response", "=", "get_page", "(", "token", ")", "token", "=", "response", ".", "headers", ".", "get", "(", "\"x-next-token\"", ")", "except", "PureError", "as", "err", ":", "yield", "None", ",", "err", "else", ":", "if", "response", ":", "sent_token", "=", "yield", "response", ",", "None", "if", "sent_token", "is", "not", "None", ":", "token", "=", "sent_token", "else", ":", "return", "return", "page_generator", "(", ")" ]
Return an iterator over all pages of a REST operation. :param page_size: Number of elements to retrieve per call. :param function: FlashArray function that accepts limit as an argument. :param \*args: Positional arguments to be passed to function. :param \*\*kwargs: Keyword arguments to be passed to function. :returns: An iterator of tuples containing a page of results for the function(\*args, \*\*kwargs) and None, or None and a PureError if a call to retrieve a page fails. :rtype: iterator .. note:: Requires use of REST API 1.7 or later. Only works with functions that accept limit as an argument. Iterator will retrieve page_size elements per call Iterator will yield None and an error if a call fails. The next call will repeat the same call, unless the caller sends in an alternate page token.
[ "Return", "an", "iterator", "over", "all", "pages", "of", "a", "REST", "operation", "." ]
097d5f2bc6facf607d7e4a92567b09fb8cf5cb34
https://github.com/PureStorage-OpenConnect/rest-client/blob/097d5f2bc6facf607d7e4a92567b09fb8cf5cb34/purestorage/purestorage.py#L3632-L3683
train
bitprophet/ssh
ssh/sftp_server.py
SFTPServer.set_file_attr
def set_file_attr(filename, attr): """ Change a file's attributes on the local filesystem. The contents of C{attr} are used to change the permissions, owner, group ownership, and/or modification & access time of the file, depending on which attributes are present in C{attr}. This is meant to be a handy helper function for translating SFTP file requests into local file operations. @param filename: name of the file to alter (should usually be an absolute path). @type filename: str @param attr: attributes to change. @type attr: L{SFTPAttributes} """ if sys.platform != 'win32': # mode operations are meaningless on win32 if attr._flags & attr.FLAG_PERMISSIONS: os.chmod(filename, attr.st_mode) if attr._flags & attr.FLAG_UIDGID: os.chown(filename, attr.st_uid, attr.st_gid) if attr._flags & attr.FLAG_AMTIME: os.utime(filename, (attr.st_atime, attr.st_mtime)) if attr._flags & attr.FLAG_SIZE: open(filename, 'w+').truncate(attr.st_size)
python
def set_file_attr(filename, attr): """ Change a file's attributes on the local filesystem. The contents of C{attr} are used to change the permissions, owner, group ownership, and/or modification & access time of the file, depending on which attributes are present in C{attr}. This is meant to be a handy helper function for translating SFTP file requests into local file operations. @param filename: name of the file to alter (should usually be an absolute path). @type filename: str @param attr: attributes to change. @type attr: L{SFTPAttributes} """ if sys.platform != 'win32': # mode operations are meaningless on win32 if attr._flags & attr.FLAG_PERMISSIONS: os.chmod(filename, attr.st_mode) if attr._flags & attr.FLAG_UIDGID: os.chown(filename, attr.st_uid, attr.st_gid) if attr._flags & attr.FLAG_AMTIME: os.utime(filename, (attr.st_atime, attr.st_mtime)) if attr._flags & attr.FLAG_SIZE: open(filename, 'w+').truncate(attr.st_size)
[ "def", "set_file_attr", "(", "filename", ",", "attr", ")", ":", "if", "sys", ".", "platform", "!=", "'win32'", ":", "# mode operations are meaningless on win32", "if", "attr", ".", "_flags", "&", "attr", ".", "FLAG_PERMISSIONS", ":", "os", ".", "chmod", "(", "filename", ",", "attr", ".", "st_mode", ")", "if", "attr", ".", "_flags", "&", "attr", ".", "FLAG_UIDGID", ":", "os", ".", "chown", "(", "filename", ",", "attr", ".", "st_uid", ",", "attr", ".", "st_gid", ")", "if", "attr", ".", "_flags", "&", "attr", ".", "FLAG_AMTIME", ":", "os", ".", "utime", "(", "filename", ",", "(", "attr", ".", "st_atime", ",", "attr", ".", "st_mtime", ")", ")", "if", "attr", ".", "_flags", "&", "attr", ".", "FLAG_SIZE", ":", "open", "(", "filename", ",", "'w+'", ")", ".", "truncate", "(", "attr", ".", "st_size", ")" ]
Change a file's attributes on the local filesystem. The contents of C{attr} are used to change the permissions, owner, group ownership, and/or modification & access time of the file, depending on which attributes are present in C{attr}. This is meant to be a handy helper function for translating SFTP file requests into local file operations. @param filename: name of the file to alter (should usually be an absolute path). @type filename: str @param attr: attributes to change. @type attr: L{SFTPAttributes}
[ "Change", "a", "file", "s", "attributes", "on", "the", "local", "filesystem", ".", "The", "contents", "of", "C", "{", "attr", "}", "are", "used", "to", "change", "the", "permissions", "owner", "group", "ownership", "and", "/", "or", "modification", "&", "access", "time", "of", "the", "file", "depending", "on", "which", "attributes", "are", "present", "in", "C", "{", "attr", "}", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/sftp_server.py#L144-L169
train
bitprophet/ssh
ssh/packet.py
Packetizer.read_all
def read_all(self, n, check_rekey=False): """ Read as close to N bytes as possible, blocking as long as necessary. @param n: number of bytes to read @type n: int @return: the data read @rtype: str @raise EOFError: if the socket was closed before all the bytes could be read """ out = '' # handle over-reading from reading the banner line if len(self.__remainder) > 0: out = self.__remainder[:n] self.__remainder = self.__remainder[n:] n -= len(out) if PY22: return self._py22_read_all(n, out) while n > 0: got_timeout = False try: x = self.__socket.recv(n) if len(x) == 0: raise EOFError() out += x n -= len(x) except socket.timeout: got_timeout = True except socket.error, e: # on Linux, sometimes instead of socket.timeout, we get # EAGAIN. this is a bug in recent (> 2.6.9) kernels but # we need to work around it. if (type(e.args) is tuple) and (len(e.args) > 0) and (e.args[0] == errno.EAGAIN): got_timeout = True elif (type(e.args) is tuple) and (len(e.args) > 0) and (e.args[0] == errno.EINTR): # syscall interrupted; try again pass elif self.__closed: raise EOFError() else: raise if got_timeout: if self.__closed: raise EOFError() if check_rekey and (len(out) == 0) and self.__need_rekey: raise NeedRekeyException() self._check_keepalive() return out
python
def read_all(self, n, check_rekey=False): """ Read as close to N bytes as possible, blocking as long as necessary. @param n: number of bytes to read @type n: int @return: the data read @rtype: str @raise EOFError: if the socket was closed before all the bytes could be read """ out = '' # handle over-reading from reading the banner line if len(self.__remainder) > 0: out = self.__remainder[:n] self.__remainder = self.__remainder[n:] n -= len(out) if PY22: return self._py22_read_all(n, out) while n > 0: got_timeout = False try: x = self.__socket.recv(n) if len(x) == 0: raise EOFError() out += x n -= len(x) except socket.timeout: got_timeout = True except socket.error, e: # on Linux, sometimes instead of socket.timeout, we get # EAGAIN. this is a bug in recent (> 2.6.9) kernels but # we need to work around it. if (type(e.args) is tuple) and (len(e.args) > 0) and (e.args[0] == errno.EAGAIN): got_timeout = True elif (type(e.args) is tuple) and (len(e.args) > 0) and (e.args[0] == errno.EINTR): # syscall interrupted; try again pass elif self.__closed: raise EOFError() else: raise if got_timeout: if self.__closed: raise EOFError() if check_rekey and (len(out) == 0) and self.__need_rekey: raise NeedRekeyException() self._check_keepalive() return out
[ "def", "read_all", "(", "self", ",", "n", ",", "check_rekey", "=", "False", ")", ":", "out", "=", "''", "# handle over-reading from reading the banner line", "if", "len", "(", "self", ".", "__remainder", ")", ">", "0", ":", "out", "=", "self", ".", "__remainder", "[", ":", "n", "]", "self", ".", "__remainder", "=", "self", ".", "__remainder", "[", "n", ":", "]", "n", "-=", "len", "(", "out", ")", "if", "PY22", ":", "return", "self", ".", "_py22_read_all", "(", "n", ",", "out", ")", "while", "n", ">", "0", ":", "got_timeout", "=", "False", "try", ":", "x", "=", "self", ".", "__socket", ".", "recv", "(", "n", ")", "if", "len", "(", "x", ")", "==", "0", ":", "raise", "EOFError", "(", ")", "out", "+=", "x", "n", "-=", "len", "(", "x", ")", "except", "socket", ".", "timeout", ":", "got_timeout", "=", "True", "except", "socket", ".", "error", ",", "e", ":", "# on Linux, sometimes instead of socket.timeout, we get", "# EAGAIN. this is a bug in recent (> 2.6.9) kernels but", "# we need to work around it.", "if", "(", "type", "(", "e", ".", "args", ")", "is", "tuple", ")", "and", "(", "len", "(", "e", ".", "args", ")", ">", "0", ")", "and", "(", "e", ".", "args", "[", "0", "]", "==", "errno", ".", "EAGAIN", ")", ":", "got_timeout", "=", "True", "elif", "(", "type", "(", "e", ".", "args", ")", "is", "tuple", ")", "and", "(", "len", "(", "e", ".", "args", ")", ">", "0", ")", "and", "(", "e", ".", "args", "[", "0", "]", "==", "errno", ".", "EINTR", ")", ":", "# syscall interrupted; try again", "pass", "elif", "self", ".", "__closed", ":", "raise", "EOFError", "(", ")", "else", ":", "raise", "if", "got_timeout", ":", "if", "self", ".", "__closed", ":", "raise", "EOFError", "(", ")", "if", "check_rekey", "and", "(", "len", "(", "out", ")", "==", "0", ")", "and", "self", ".", "__need_rekey", ":", "raise", "NeedRekeyException", "(", ")", "self", ".", "_check_keepalive", "(", ")", "return", "out" ]
Read as close to N bytes as possible, blocking as long as necessary. @param n: number of bytes to read @type n: int @return: the data read @rtype: str @raise EOFError: if the socket was closed before all the bytes could be read
[ "Read", "as", "close", "to", "N", "bytes", "as", "possible", "blocking", "as", "long", "as", "necessary", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/packet.py#L191-L239
train
bitprophet/ssh
ssh/packet.py
Packetizer.readline
def readline(self, timeout): """ Read a line from the socket. We assume no data is pending after the line, so it's okay to attempt large reads. """ buf = self.__remainder while not '\n' in buf: buf += self._read_timeout(timeout) n = buf.index('\n') self.__remainder = buf[n+1:] buf = buf[:n] if (len(buf) > 0) and (buf[-1] == '\r'): buf = buf[:-1] return buf
python
def readline(self, timeout): """ Read a line from the socket. We assume no data is pending after the line, so it's okay to attempt large reads. """ buf = self.__remainder while not '\n' in buf: buf += self._read_timeout(timeout) n = buf.index('\n') self.__remainder = buf[n+1:] buf = buf[:n] if (len(buf) > 0) and (buf[-1] == '\r'): buf = buf[:-1] return buf
[ "def", "readline", "(", "self", ",", "timeout", ")", ":", "buf", "=", "self", ".", "__remainder", "while", "not", "'\\n'", "in", "buf", ":", "buf", "+=", "self", ".", "_read_timeout", "(", "timeout", ")", "n", "=", "buf", ".", "index", "(", "'\\n'", ")", "self", ".", "__remainder", "=", "buf", "[", "n", "+", "1", ":", "]", "buf", "=", "buf", "[", ":", "n", "]", "if", "(", "len", "(", "buf", ")", ">", "0", ")", "and", "(", "buf", "[", "-", "1", "]", "==", "'\\r'", ")", ":", "buf", "=", "buf", "[", ":", "-", "1", "]", "return", "buf" ]
Read a line from the socket. We assume no data is pending after the line, so it's okay to attempt large reads.
[ "Read", "a", "line", "from", "the", "socket", ".", "We", "assume", "no", "data", "is", "pending", "after", "the", "line", "so", "it", "s", "okay", "to", "attempt", "large", "reads", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/packet.py#L271-L284
train
bitprophet/ssh
ssh/packet.py
Packetizer.send_message
def send_message(self, data): """ Write a block of data using the current cipher, as an SSH block. """ # encrypt this sucka data = str(data) cmd = ord(data[0]) if cmd in MSG_NAMES: cmd_name = MSG_NAMES[cmd] else: cmd_name = '$%x' % cmd orig_len = len(data) self.__write_lock.acquire() try: if self.__compress_engine_out is not None: data = self.__compress_engine_out(data) packet = self._build_packet(data) if self.__dump_packets: self._log(DEBUG, 'Write packet <%s>, length %d' % (cmd_name, orig_len)) self._log(DEBUG, util.format_binary(packet, 'OUT: ')) if self.__block_engine_out != None: out = self.__block_engine_out.encrypt(packet) else: out = packet # + mac if self.__block_engine_out != None: payload = struct.pack('>I', self.__sequence_number_out) + packet out += compute_hmac(self.__mac_key_out, payload, self.__mac_engine_out)[:self.__mac_size_out] self.__sequence_number_out = (self.__sequence_number_out + 1) & 0xffffffffL self.write_all(out) self.__sent_bytes += len(out) self.__sent_packets += 1 if ((self.__sent_packets >= self.REKEY_PACKETS) or (self.__sent_bytes >= self.REKEY_BYTES)) \ and not self.__need_rekey: # only ask once for rekeying self._log(DEBUG, 'Rekeying (hit %d packets, %d bytes sent)' % (self.__sent_packets, self.__sent_bytes)) self.__received_bytes_overflow = 0 self.__received_packets_overflow = 0 self._trigger_rekey() finally: self.__write_lock.release()
python
def send_message(self, data): """ Write a block of data using the current cipher, as an SSH block. """ # encrypt this sucka data = str(data) cmd = ord(data[0]) if cmd in MSG_NAMES: cmd_name = MSG_NAMES[cmd] else: cmd_name = '$%x' % cmd orig_len = len(data) self.__write_lock.acquire() try: if self.__compress_engine_out is not None: data = self.__compress_engine_out(data) packet = self._build_packet(data) if self.__dump_packets: self._log(DEBUG, 'Write packet <%s>, length %d' % (cmd_name, orig_len)) self._log(DEBUG, util.format_binary(packet, 'OUT: ')) if self.__block_engine_out != None: out = self.__block_engine_out.encrypt(packet) else: out = packet # + mac if self.__block_engine_out != None: payload = struct.pack('>I', self.__sequence_number_out) + packet out += compute_hmac(self.__mac_key_out, payload, self.__mac_engine_out)[:self.__mac_size_out] self.__sequence_number_out = (self.__sequence_number_out + 1) & 0xffffffffL self.write_all(out) self.__sent_bytes += len(out) self.__sent_packets += 1 if ((self.__sent_packets >= self.REKEY_PACKETS) or (self.__sent_bytes >= self.REKEY_BYTES)) \ and not self.__need_rekey: # only ask once for rekeying self._log(DEBUG, 'Rekeying (hit %d packets, %d bytes sent)' % (self.__sent_packets, self.__sent_bytes)) self.__received_bytes_overflow = 0 self.__received_packets_overflow = 0 self._trigger_rekey() finally: self.__write_lock.release()
[ "def", "send_message", "(", "self", ",", "data", ")", ":", "# encrypt this sucka", "data", "=", "str", "(", "data", ")", "cmd", "=", "ord", "(", "data", "[", "0", "]", ")", "if", "cmd", "in", "MSG_NAMES", ":", "cmd_name", "=", "MSG_NAMES", "[", "cmd", "]", "else", ":", "cmd_name", "=", "'$%x'", "%", "cmd", "orig_len", "=", "len", "(", "data", ")", "self", ".", "__write_lock", ".", "acquire", "(", ")", "try", ":", "if", "self", ".", "__compress_engine_out", "is", "not", "None", ":", "data", "=", "self", ".", "__compress_engine_out", "(", "data", ")", "packet", "=", "self", ".", "_build_packet", "(", "data", ")", "if", "self", ".", "__dump_packets", ":", "self", ".", "_log", "(", "DEBUG", ",", "'Write packet <%s>, length %d'", "%", "(", "cmd_name", ",", "orig_len", ")", ")", "self", ".", "_log", "(", "DEBUG", ",", "util", ".", "format_binary", "(", "packet", ",", "'OUT: '", ")", ")", "if", "self", ".", "__block_engine_out", "!=", "None", ":", "out", "=", "self", ".", "__block_engine_out", ".", "encrypt", "(", "packet", ")", "else", ":", "out", "=", "packet", "# + mac", "if", "self", ".", "__block_engine_out", "!=", "None", ":", "payload", "=", "struct", ".", "pack", "(", "'>I'", ",", "self", ".", "__sequence_number_out", ")", "+", "packet", "out", "+=", "compute_hmac", "(", "self", ".", "__mac_key_out", ",", "payload", ",", "self", ".", "__mac_engine_out", ")", "[", ":", "self", ".", "__mac_size_out", "]", "self", ".", "__sequence_number_out", "=", "(", "self", ".", "__sequence_number_out", "+", "1", ")", "&", "0xffffffffL", "self", ".", "write_all", "(", "out", ")", "self", ".", "__sent_bytes", "+=", "len", "(", "out", ")", "self", ".", "__sent_packets", "+=", "1", "if", "(", "(", "self", ".", "__sent_packets", ">=", "self", ".", "REKEY_PACKETS", ")", "or", "(", "self", ".", "__sent_bytes", ">=", "self", ".", "REKEY_BYTES", ")", ")", "and", "not", "self", ".", "__need_rekey", ":", "# only ask once for rekeying", "self", ".", "_log", "(", "DEBUG", ",", "'Rekeying (hit %d packets, %d bytes sent)'", "%", "(", "self", ".", "__sent_packets", ",", "self", ".", "__sent_bytes", ")", ")", "self", ".", "__received_bytes_overflow", "=", "0", "self", ".", "__received_packets_overflow", "=", "0", "self", ".", "_trigger_rekey", "(", ")", "finally", ":", "self", ".", "__write_lock", ".", "release", "(", ")" ]
Write a block of data using the current cipher, as an SSH block.
[ "Write", "a", "block", "of", "data", "using", "the", "current", "cipher", "as", "an", "SSH", "block", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/packet.py#L286-L328
train
bitprophet/ssh
ssh/packet.py
Packetizer.read_message
def read_message(self): """ Only one thread should ever be in this function (no other locking is done). @raise SSHException: if the packet is mangled @raise NeedRekeyException: if the transport should rekey """ header = self.read_all(self.__block_size_in, check_rekey=True) if self.__block_engine_in != None: header = self.__block_engine_in.decrypt(header) if self.__dump_packets: self._log(DEBUG, util.format_binary(header, 'IN: ')); packet_size = struct.unpack('>I', header[:4])[0] # leftover contains decrypted bytes from the first block (after the length field) leftover = header[4:] if (packet_size - len(leftover)) % self.__block_size_in != 0: raise SSHException('Invalid packet blocking') buf = self.read_all(packet_size + self.__mac_size_in - len(leftover)) packet = buf[:packet_size - len(leftover)] post_packet = buf[packet_size - len(leftover):] if self.__block_engine_in != None: packet = self.__block_engine_in.decrypt(packet) if self.__dump_packets: self._log(DEBUG, util.format_binary(packet, 'IN: ')); packet = leftover + packet if self.__mac_size_in > 0: mac = post_packet[:self.__mac_size_in] mac_payload = struct.pack('>II', self.__sequence_number_in, packet_size) + packet my_mac = compute_hmac(self.__mac_key_in, mac_payload, self.__mac_engine_in)[:self.__mac_size_in] if my_mac != mac: raise SSHException('Mismatched MAC') padding = ord(packet[0]) payload = packet[1:packet_size - padding] if self.__dump_packets: self._log(DEBUG, 'Got payload (%d bytes, %d padding)' % (packet_size, padding)) if self.__compress_engine_in is not None: payload = self.__compress_engine_in(payload) msg = Message(payload[1:]) msg.seqno = self.__sequence_number_in self.__sequence_number_in = (self.__sequence_number_in + 1) & 0xffffffffL # check for rekey raw_packet_size = packet_size + self.__mac_size_in + 4 self.__received_bytes += raw_packet_size self.__received_packets += 1 if self.__need_rekey: # we've asked to rekey -- give them some packets to comply before # dropping the connection self.__received_bytes_overflow += raw_packet_size self.__received_packets_overflow += 1 if (self.__received_packets_overflow >= self.REKEY_PACKETS_OVERFLOW_MAX) or \ (self.__received_bytes_overflow >= self.REKEY_BYTES_OVERFLOW_MAX): raise SSHException('Remote transport is ignoring rekey requests') elif (self.__received_packets >= self.REKEY_PACKETS) or \ (self.__received_bytes >= self.REKEY_BYTES): # only ask once for rekeying self._log(DEBUG, 'Rekeying (hit %d packets, %d bytes received)' % (self.__received_packets, self.__received_bytes)) self.__received_bytes_overflow = 0 self.__received_packets_overflow = 0 self._trigger_rekey() cmd = ord(payload[0]) if cmd in MSG_NAMES: cmd_name = MSG_NAMES[cmd] else: cmd_name = '$%x' % cmd if self.__dump_packets: self._log(DEBUG, 'Read packet <%s>, length %d' % (cmd_name, len(payload))) return cmd, msg
python
def read_message(self): """ Only one thread should ever be in this function (no other locking is done). @raise SSHException: if the packet is mangled @raise NeedRekeyException: if the transport should rekey """ header = self.read_all(self.__block_size_in, check_rekey=True) if self.__block_engine_in != None: header = self.__block_engine_in.decrypt(header) if self.__dump_packets: self._log(DEBUG, util.format_binary(header, 'IN: ')); packet_size = struct.unpack('>I', header[:4])[0] # leftover contains decrypted bytes from the first block (after the length field) leftover = header[4:] if (packet_size - len(leftover)) % self.__block_size_in != 0: raise SSHException('Invalid packet blocking') buf = self.read_all(packet_size + self.__mac_size_in - len(leftover)) packet = buf[:packet_size - len(leftover)] post_packet = buf[packet_size - len(leftover):] if self.__block_engine_in != None: packet = self.__block_engine_in.decrypt(packet) if self.__dump_packets: self._log(DEBUG, util.format_binary(packet, 'IN: ')); packet = leftover + packet if self.__mac_size_in > 0: mac = post_packet[:self.__mac_size_in] mac_payload = struct.pack('>II', self.__sequence_number_in, packet_size) + packet my_mac = compute_hmac(self.__mac_key_in, mac_payload, self.__mac_engine_in)[:self.__mac_size_in] if my_mac != mac: raise SSHException('Mismatched MAC') padding = ord(packet[0]) payload = packet[1:packet_size - padding] if self.__dump_packets: self._log(DEBUG, 'Got payload (%d bytes, %d padding)' % (packet_size, padding)) if self.__compress_engine_in is not None: payload = self.__compress_engine_in(payload) msg = Message(payload[1:]) msg.seqno = self.__sequence_number_in self.__sequence_number_in = (self.__sequence_number_in + 1) & 0xffffffffL # check for rekey raw_packet_size = packet_size + self.__mac_size_in + 4 self.__received_bytes += raw_packet_size self.__received_packets += 1 if self.__need_rekey: # we've asked to rekey -- give them some packets to comply before # dropping the connection self.__received_bytes_overflow += raw_packet_size self.__received_packets_overflow += 1 if (self.__received_packets_overflow >= self.REKEY_PACKETS_OVERFLOW_MAX) or \ (self.__received_bytes_overflow >= self.REKEY_BYTES_OVERFLOW_MAX): raise SSHException('Remote transport is ignoring rekey requests') elif (self.__received_packets >= self.REKEY_PACKETS) or \ (self.__received_bytes >= self.REKEY_BYTES): # only ask once for rekeying self._log(DEBUG, 'Rekeying (hit %d packets, %d bytes received)' % (self.__received_packets, self.__received_bytes)) self.__received_bytes_overflow = 0 self.__received_packets_overflow = 0 self._trigger_rekey() cmd = ord(payload[0]) if cmd in MSG_NAMES: cmd_name = MSG_NAMES[cmd] else: cmd_name = '$%x' % cmd if self.__dump_packets: self._log(DEBUG, 'Read packet <%s>, length %d' % (cmd_name, len(payload))) return cmd, msg
[ "def", "read_message", "(", "self", ")", ":", "header", "=", "self", ".", "read_all", "(", "self", ".", "__block_size_in", ",", "check_rekey", "=", "True", ")", "if", "self", ".", "__block_engine_in", "!=", "None", ":", "header", "=", "self", ".", "__block_engine_in", ".", "decrypt", "(", "header", ")", "if", "self", ".", "__dump_packets", ":", "self", ".", "_log", "(", "DEBUG", ",", "util", ".", "format_binary", "(", "header", ",", "'IN: '", ")", ")", "packet_size", "=", "struct", ".", "unpack", "(", "'>I'", ",", "header", "[", ":", "4", "]", ")", "[", "0", "]", "# leftover contains decrypted bytes from the first block (after the length field)", "leftover", "=", "header", "[", "4", ":", "]", "if", "(", "packet_size", "-", "len", "(", "leftover", ")", ")", "%", "self", ".", "__block_size_in", "!=", "0", ":", "raise", "SSHException", "(", "'Invalid packet blocking'", ")", "buf", "=", "self", ".", "read_all", "(", "packet_size", "+", "self", ".", "__mac_size_in", "-", "len", "(", "leftover", ")", ")", "packet", "=", "buf", "[", ":", "packet_size", "-", "len", "(", "leftover", ")", "]", "post_packet", "=", "buf", "[", "packet_size", "-", "len", "(", "leftover", ")", ":", "]", "if", "self", ".", "__block_engine_in", "!=", "None", ":", "packet", "=", "self", ".", "__block_engine_in", ".", "decrypt", "(", "packet", ")", "if", "self", ".", "__dump_packets", ":", "self", ".", "_log", "(", "DEBUG", ",", "util", ".", "format_binary", "(", "packet", ",", "'IN: '", ")", ")", "packet", "=", "leftover", "+", "packet", "if", "self", ".", "__mac_size_in", ">", "0", ":", "mac", "=", "post_packet", "[", ":", "self", ".", "__mac_size_in", "]", "mac_payload", "=", "struct", ".", "pack", "(", "'>II'", ",", "self", ".", "__sequence_number_in", ",", "packet_size", ")", "+", "packet", "my_mac", "=", "compute_hmac", "(", "self", ".", "__mac_key_in", ",", "mac_payload", ",", "self", ".", "__mac_engine_in", ")", "[", ":", "self", ".", "__mac_size_in", "]", "if", "my_mac", "!=", "mac", ":", "raise", "SSHException", "(", "'Mismatched MAC'", ")", "padding", "=", "ord", "(", "packet", "[", "0", "]", ")", "payload", "=", "packet", "[", "1", ":", "packet_size", "-", "padding", "]", "if", "self", ".", "__dump_packets", ":", "self", ".", "_log", "(", "DEBUG", ",", "'Got payload (%d bytes, %d padding)'", "%", "(", "packet_size", ",", "padding", ")", ")", "if", "self", ".", "__compress_engine_in", "is", "not", "None", ":", "payload", "=", "self", ".", "__compress_engine_in", "(", "payload", ")", "msg", "=", "Message", "(", "payload", "[", "1", ":", "]", ")", "msg", ".", "seqno", "=", "self", ".", "__sequence_number_in", "self", ".", "__sequence_number_in", "=", "(", "self", ".", "__sequence_number_in", "+", "1", ")", "&", "0xffffffffL", "# check for rekey", "raw_packet_size", "=", "packet_size", "+", "self", ".", "__mac_size_in", "+", "4", "self", ".", "__received_bytes", "+=", "raw_packet_size", "self", ".", "__received_packets", "+=", "1", "if", "self", ".", "__need_rekey", ":", "# we've asked to rekey -- give them some packets to comply before", "# dropping the connection", "self", ".", "__received_bytes_overflow", "+=", "raw_packet_size", "self", ".", "__received_packets_overflow", "+=", "1", "if", "(", "self", ".", "__received_packets_overflow", ">=", "self", ".", "REKEY_PACKETS_OVERFLOW_MAX", ")", "or", "(", "self", ".", "__received_bytes_overflow", ">=", "self", ".", "REKEY_BYTES_OVERFLOW_MAX", ")", ":", "raise", "SSHException", "(", "'Remote transport is ignoring rekey requests'", ")", "elif", "(", "self", ".", "__received_packets", ">=", "self", ".", "REKEY_PACKETS", ")", "or", "(", "self", ".", "__received_bytes", ">=", "self", ".", "REKEY_BYTES", ")", ":", "# only ask once for rekeying", "self", ".", "_log", "(", "DEBUG", ",", "'Rekeying (hit %d packets, %d bytes received)'", "%", "(", "self", ".", "__received_packets", ",", "self", ".", "__received_bytes", ")", ")", "self", ".", "__received_bytes_overflow", "=", "0", "self", ".", "__received_packets_overflow", "=", "0", "self", ".", "_trigger_rekey", "(", ")", "cmd", "=", "ord", "(", "payload", "[", "0", "]", ")", "if", "cmd", "in", "MSG_NAMES", ":", "cmd_name", "=", "MSG_NAMES", "[", "cmd", "]", "else", ":", "cmd_name", "=", "'$%x'", "%", "cmd", "if", "self", ".", "__dump_packets", ":", "self", ".", "_log", "(", "DEBUG", ",", "'Read packet <%s>, length %d'", "%", "(", "cmd_name", ",", "len", "(", "payload", ")", ")", ")", "return", "cmd", ",", "msg" ]
Only one thread should ever be in this function (no other locking is done). @raise SSHException: if the packet is mangled @raise NeedRekeyException: if the transport should rekey
[ "Only", "one", "thread", "should", "ever", "be", "in", "this", "function", "(", "no", "other", "locking", "is", "done", ")", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/packet.py#L330-L404
train
bitprophet/ssh
setup_helper.py
make_tarball
def make_tarball(base_name, base_dir, compress='gzip', verbose=False, dry_run=False): """Create a tar file from all the files under 'base_dir'. This file may be compressed. :param compress: Compression algorithms. Supported algorithms are: 'gzip': (the default) 'compress' 'bzip2' None For 'gzip' and 'bzip2' the internal tarfile module will be used. For 'compress' the .tar will be created using tarfile, and then we will spawn 'compress' afterwards. The output tar file will be named 'base_name' + ".tar", possibly plus the appropriate compression extension (".gz", ".bz2" or ".Z"). Return the output filename. """ # XXX GNU tar 1.13 has a nifty option to add a prefix directory. # It's pretty new, though, so we certainly can't require it -- # but it would be nice to take advantage of it to skip the # "create a tree of hardlinks" step! (Would also be nice to # detect GNU tar to use its 'z' option and save a step.) compress_ext = { 'gzip': ".gz", 'bzip2': '.bz2', 'compress': ".Z" } # flags for compression program, each element of list will be an argument tarfile_compress_flag = {'gzip':'gz', 'bzip2':'bz2'} compress_flags = {'compress': ["-f"]} if compress is not None and compress not in compress_ext.keys(): raise ValueError("bad value for 'compress': must be None, 'gzip'," "'bzip2' or 'compress'") archive_name = base_name + ".tar" if compress and compress in tarfile_compress_flag: archive_name += compress_ext[compress] mode = 'w:' + tarfile_compress_flag.get(compress, '') mkpath(os.path.dirname(archive_name), dry_run=dry_run) log.info('Creating tar file %s with mode %s' % (archive_name, mode)) if not dry_run: tar = tarfile.open(archive_name, mode=mode) # This recursively adds everything underneath base_dir tar.add(base_dir) tar.close() if compress and compress not in tarfile_compress_flag: spawn([compress] + compress_flags[compress] + [archive_name], dry_run=dry_run) return archive_name + compress_ext[compress] else: return archive_name
python
def make_tarball(base_name, base_dir, compress='gzip', verbose=False, dry_run=False): """Create a tar file from all the files under 'base_dir'. This file may be compressed. :param compress: Compression algorithms. Supported algorithms are: 'gzip': (the default) 'compress' 'bzip2' None For 'gzip' and 'bzip2' the internal tarfile module will be used. For 'compress' the .tar will be created using tarfile, and then we will spawn 'compress' afterwards. The output tar file will be named 'base_name' + ".tar", possibly plus the appropriate compression extension (".gz", ".bz2" or ".Z"). Return the output filename. """ # XXX GNU tar 1.13 has a nifty option to add a prefix directory. # It's pretty new, though, so we certainly can't require it -- # but it would be nice to take advantage of it to skip the # "create a tree of hardlinks" step! (Would also be nice to # detect GNU tar to use its 'z' option and save a step.) compress_ext = { 'gzip': ".gz", 'bzip2': '.bz2', 'compress': ".Z" } # flags for compression program, each element of list will be an argument tarfile_compress_flag = {'gzip':'gz', 'bzip2':'bz2'} compress_flags = {'compress': ["-f"]} if compress is not None and compress not in compress_ext.keys(): raise ValueError("bad value for 'compress': must be None, 'gzip'," "'bzip2' or 'compress'") archive_name = base_name + ".tar" if compress and compress in tarfile_compress_flag: archive_name += compress_ext[compress] mode = 'w:' + tarfile_compress_flag.get(compress, '') mkpath(os.path.dirname(archive_name), dry_run=dry_run) log.info('Creating tar file %s with mode %s' % (archive_name, mode)) if not dry_run: tar = tarfile.open(archive_name, mode=mode) # This recursively adds everything underneath base_dir tar.add(base_dir) tar.close() if compress and compress not in tarfile_compress_flag: spawn([compress] + compress_flags[compress] + [archive_name], dry_run=dry_run) return archive_name + compress_ext[compress] else: return archive_name
[ "def", "make_tarball", "(", "base_name", ",", "base_dir", ",", "compress", "=", "'gzip'", ",", "verbose", "=", "False", ",", "dry_run", "=", "False", ")", ":", "# XXX GNU tar 1.13 has a nifty option to add a prefix directory.", "# It's pretty new, though, so we certainly can't require it --", "# but it would be nice to take advantage of it to skip the", "# \"create a tree of hardlinks\" step! (Would also be nice to", "# detect GNU tar to use its 'z' option and save a step.)", "compress_ext", "=", "{", "'gzip'", ":", "\".gz\"", ",", "'bzip2'", ":", "'.bz2'", ",", "'compress'", ":", "\".Z\"", "}", "# flags for compression program, each element of list will be an argument", "tarfile_compress_flag", "=", "{", "'gzip'", ":", "'gz'", ",", "'bzip2'", ":", "'bz2'", "}", "compress_flags", "=", "{", "'compress'", ":", "[", "\"-f\"", "]", "}", "if", "compress", "is", "not", "None", "and", "compress", "not", "in", "compress_ext", ".", "keys", "(", ")", ":", "raise", "ValueError", "(", "\"bad value for 'compress': must be None, 'gzip',\"", "\"'bzip2' or 'compress'\"", ")", "archive_name", "=", "base_name", "+", "\".tar\"", "if", "compress", "and", "compress", "in", "tarfile_compress_flag", ":", "archive_name", "+=", "compress_ext", "[", "compress", "]", "mode", "=", "'w:'", "+", "tarfile_compress_flag", ".", "get", "(", "compress", ",", "''", ")", "mkpath", "(", "os", ".", "path", ".", "dirname", "(", "archive_name", ")", ",", "dry_run", "=", "dry_run", ")", "log", ".", "info", "(", "'Creating tar file %s with mode %s'", "%", "(", "archive_name", ",", "mode", ")", ")", "if", "not", "dry_run", ":", "tar", "=", "tarfile", ".", "open", "(", "archive_name", ",", "mode", "=", "mode", ")", "# This recursively adds everything underneath base_dir", "tar", ".", "add", "(", "base_dir", ")", "tar", ".", "close", "(", ")", "if", "compress", "and", "compress", "not", "in", "tarfile_compress_flag", ":", "spawn", "(", "[", "compress", "]", "+", "compress_flags", "[", "compress", "]", "+", "[", "archive_name", "]", ",", "dry_run", "=", "dry_run", ")", "return", "archive_name", "+", "compress_ext", "[", "compress", "]", "else", ":", "return", "archive_name" ]
Create a tar file from all the files under 'base_dir'. This file may be compressed. :param compress: Compression algorithms. Supported algorithms are: 'gzip': (the default) 'compress' 'bzip2' None For 'gzip' and 'bzip2' the internal tarfile module will be used. For 'compress' the .tar will be created using tarfile, and then we will spawn 'compress' afterwards. The output tar file will be named 'base_name' + ".tar", possibly plus the appropriate compression extension (".gz", ".bz2" or ".Z"). Return the output filename.
[ "Create", "a", "tar", "file", "from", "all", "the", "files", "under", "base_dir", ".", "This", "file", "may", "be", "compressed", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/setup_helper.py#L34-L89
train
bitprophet/ssh
ssh/auth_handler.py
AuthHandler.auth_interactive
def auth_interactive(self, username, handler, event, submethods=''): """ response_list = handler(title, instructions, prompt_list) """ self.transport.lock.acquire() try: self.auth_event = event self.auth_method = 'keyboard-interactive' self.username = username self.interactive_handler = handler self.submethods = submethods self._request_auth() finally: self.transport.lock.release()
python
def auth_interactive(self, username, handler, event, submethods=''): """ response_list = handler(title, instructions, prompt_list) """ self.transport.lock.acquire() try: self.auth_event = event self.auth_method = 'keyboard-interactive' self.username = username self.interactive_handler = handler self.submethods = submethods self._request_auth() finally: self.transport.lock.release()
[ "def", "auth_interactive", "(", "self", ",", "username", ",", "handler", ",", "event", ",", "submethods", "=", "''", ")", ":", "self", ".", "transport", ".", "lock", ".", "acquire", "(", ")", "try", ":", "self", ".", "auth_event", "=", "event", "self", ".", "auth_method", "=", "'keyboard-interactive'", "self", ".", "username", "=", "username", "self", ".", "interactive_handler", "=", "handler", "self", ".", "submethods", "=", "submethods", "self", ".", "_request_auth", "(", ")", "finally", ":", "self", ".", "transport", ".", "lock", ".", "release", "(", ")" ]
response_list = handler(title, instructions, prompt_list)
[ "response_list", "=", "handler", "(", "title", "instructions", "prompt_list", ")" ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/auth_handler.py#L97-L110
train
bitprophet/ssh
ssh/hostkeys.py
HostKeyEntry.from_line
def from_line(cls, line): """ Parses the given line of text to find the names for the host, the type of key, and the key data. The line is expected to be in the format used by the openssh known_hosts file. Lines are expected to not have leading or trailing whitespace. We don't bother to check for comments or empty lines. All of that should be taken care of before sending the line to us. @param line: a line from an OpenSSH known_hosts file @type line: str """ fields = line.split(' ') if len(fields) < 3: # Bad number of fields return None fields = fields[:3] names, keytype, key = fields names = names.split(',') # Decide what kind of key we're looking at and create an object # to hold it accordingly. try: if keytype == 'ssh-rsa': key = RSAKey(data=base64.decodestring(key)) elif keytype == 'ssh-dss': key = DSSKey(data=base64.decodestring(key)) else: return None except binascii.Error, e: raise InvalidHostKey(line, e) return cls(names, key)
python
def from_line(cls, line): """ Parses the given line of text to find the names for the host, the type of key, and the key data. The line is expected to be in the format used by the openssh known_hosts file. Lines are expected to not have leading or trailing whitespace. We don't bother to check for comments or empty lines. All of that should be taken care of before sending the line to us. @param line: a line from an OpenSSH known_hosts file @type line: str """ fields = line.split(' ') if len(fields) < 3: # Bad number of fields return None fields = fields[:3] names, keytype, key = fields names = names.split(',') # Decide what kind of key we're looking at and create an object # to hold it accordingly. try: if keytype == 'ssh-rsa': key = RSAKey(data=base64.decodestring(key)) elif keytype == 'ssh-dss': key = DSSKey(data=base64.decodestring(key)) else: return None except binascii.Error, e: raise InvalidHostKey(line, e) return cls(names, key)
[ "def", "from_line", "(", "cls", ",", "line", ")", ":", "fields", "=", "line", ".", "split", "(", "' '", ")", "if", "len", "(", "fields", ")", "<", "3", ":", "# Bad number of fields", "return", "None", "fields", "=", "fields", "[", ":", "3", "]", "names", ",", "keytype", ",", "key", "=", "fields", "names", "=", "names", ".", "split", "(", "','", ")", "# Decide what kind of key we're looking at and create an object", "# to hold it accordingly.", "try", ":", "if", "keytype", "==", "'ssh-rsa'", ":", "key", "=", "RSAKey", "(", "data", "=", "base64", ".", "decodestring", "(", "key", ")", ")", "elif", "keytype", "==", "'ssh-dss'", ":", "key", "=", "DSSKey", "(", "data", "=", "base64", ".", "decodestring", "(", "key", ")", ")", "else", ":", "return", "None", "except", "binascii", ".", "Error", ",", "e", ":", "raise", "InvalidHostKey", "(", "line", ",", "e", ")", "return", "cls", "(", "names", ",", "key", ")" ]
Parses the given line of text to find the names for the host, the type of key, and the key data. The line is expected to be in the format used by the openssh known_hosts file. Lines are expected to not have leading or trailing whitespace. We don't bother to check for comments or empty lines. All of that should be taken care of before sending the line to us. @param line: a line from an OpenSSH known_hosts file @type line: str
[ "Parses", "the", "given", "line", "of", "text", "to", "find", "the", "names", "for", "the", "host", "the", "type", "of", "key", "and", "the", "key", "data", ".", "The", "line", "is", "expected", "to", "be", "in", "the", "format", "used", "by", "the", "openssh", "known_hosts", "file", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/hostkeys.py#L51-L85
train
bitprophet/ssh
ssh/hostkeys.py
HostKeyEntry.to_line
def to_line(self): """ Returns a string in OpenSSH known_hosts file format, or None if the object is not in a valid state. A trailing newline is included. """ if self.valid: return '%s %s %s\n' % (','.join(self.hostnames), self.key.get_name(), self.key.get_base64()) return None
python
def to_line(self): """ Returns a string in OpenSSH known_hosts file format, or None if the object is not in a valid state. A trailing newline is included. """ if self.valid: return '%s %s %s\n' % (','.join(self.hostnames), self.key.get_name(), self.key.get_base64()) return None
[ "def", "to_line", "(", "self", ")", ":", "if", "self", ".", "valid", ":", "return", "'%s %s %s\\n'", "%", "(", "','", ".", "join", "(", "self", ".", "hostnames", ")", ",", "self", ".", "key", ".", "get_name", "(", ")", ",", "self", ".", "key", ".", "get_base64", "(", ")", ")", "return", "None" ]
Returns a string in OpenSSH known_hosts file format, or None if the object is not in a valid state. A trailing newline is included.
[ "Returns", "a", "string", "in", "OpenSSH", "known_hosts", "file", "format", "or", "None", "if", "the", "object", "is", "not", "in", "a", "valid", "state", ".", "A", "trailing", "newline", "is", "included", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/hostkeys.py#L88-L97
train
bitprophet/ssh
ssh/hostkeys.py
HostKeys.load
def load(self, filename): """ Read a file of known SSH host keys, in the format used by openssh. This type of file unfortunately doesn't exist on Windows, but on posix, it will usually be stored in C{os.path.expanduser("~/.ssh/known_hosts")}. If this method is called multiple times, the host keys are merged, not cleared. So multiple calls to C{load} will just call L{add}, replacing any existing entries and adding new ones. @param filename: name of the file to read host keys from @type filename: str @raise IOError: if there was an error reading the file """ f = open(filename, 'r') for line in f: line = line.strip() if (len(line) == 0) or (line[0] == '#'): continue e = HostKeyEntry.from_line(line) if e is not None: self._entries.append(e) f.close()
python
def load(self, filename): """ Read a file of known SSH host keys, in the format used by openssh. This type of file unfortunately doesn't exist on Windows, but on posix, it will usually be stored in C{os.path.expanduser("~/.ssh/known_hosts")}. If this method is called multiple times, the host keys are merged, not cleared. So multiple calls to C{load} will just call L{add}, replacing any existing entries and adding new ones. @param filename: name of the file to read host keys from @type filename: str @raise IOError: if there was an error reading the file """ f = open(filename, 'r') for line in f: line = line.strip() if (len(line) == 0) or (line[0] == '#'): continue e = HostKeyEntry.from_line(line) if e is not None: self._entries.append(e) f.close()
[ "def", "load", "(", "self", ",", "filename", ")", ":", "f", "=", "open", "(", "filename", ",", "'r'", ")", "for", "line", "in", "f", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "(", "len", "(", "line", ")", "==", "0", ")", "or", "(", "line", "[", "0", "]", "==", "'#'", ")", ":", "continue", "e", "=", "HostKeyEntry", ".", "from_line", "(", "line", ")", "if", "e", "is", "not", "None", ":", "self", ".", "_entries", ".", "append", "(", "e", ")", "f", ".", "close", "(", ")" ]
Read a file of known SSH host keys, in the format used by openssh. This type of file unfortunately doesn't exist on Windows, but on posix, it will usually be stored in C{os.path.expanduser("~/.ssh/known_hosts")}. If this method is called multiple times, the host keys are merged, not cleared. So multiple calls to C{load} will just call L{add}, replacing any existing entries and adding new ones. @param filename: name of the file to read host keys from @type filename: str @raise IOError: if there was an error reading the file
[ "Read", "a", "file", "of", "known", "SSH", "host", "keys", "in", "the", "format", "used", "by", "openssh", ".", "This", "type", "of", "file", "unfortunately", "doesn", "t", "exist", "on", "Windows", "but", "on", "posix", "it", "will", "usually", "be", "stored", "in", "C", "{", "os", ".", "path", ".", "expanduser", "(", "~", "/", ".", "ssh", "/", "known_hosts", ")", "}", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/hostkeys.py#L146-L170
train
bitprophet/ssh
ssh/hostkeys.py
HostKeys.save
def save(self, filename): """ Save host keys into a file, in the format used by openssh. The order of keys in the file will be preserved when possible (if these keys were loaded from a file originally). The single exception is that combined lines will be split into individual key lines, which is arguably a bug. @param filename: name of the file to write @type filename: str @raise IOError: if there was an error writing the file @since: 1.6.1 """ f = open(filename, 'w') for e in self._entries: line = e.to_line() if line: f.write(line) f.close()
python
def save(self, filename): """ Save host keys into a file, in the format used by openssh. The order of keys in the file will be preserved when possible (if these keys were loaded from a file originally). The single exception is that combined lines will be split into individual key lines, which is arguably a bug. @param filename: name of the file to write @type filename: str @raise IOError: if there was an error writing the file @since: 1.6.1 """ f = open(filename, 'w') for e in self._entries: line = e.to_line() if line: f.write(line) f.close()
[ "def", "save", "(", "self", ",", "filename", ")", ":", "f", "=", "open", "(", "filename", ",", "'w'", ")", "for", "e", "in", "self", ".", "_entries", ":", "line", "=", "e", ".", "to_line", "(", ")", "if", "line", ":", "f", ".", "write", "(", "line", ")", "f", ".", "close", "(", ")" ]
Save host keys into a file, in the format used by openssh. The order of keys in the file will be preserved when possible (if these keys were loaded from a file originally). The single exception is that combined lines will be split into individual key lines, which is arguably a bug. @param filename: name of the file to write @type filename: str @raise IOError: if there was an error writing the file @since: 1.6.1
[ "Save", "host", "keys", "into", "a", "file", "in", "the", "format", "used", "by", "openssh", ".", "The", "order", "of", "keys", "in", "the", "file", "will", "be", "preserved", "when", "possible", "(", "if", "these", "keys", "were", "loaded", "from", "a", "file", "originally", ")", ".", "The", "single", "exception", "is", "that", "combined", "lines", "will", "be", "split", "into", "individual", "key", "lines", "which", "is", "arguably", "a", "bug", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/hostkeys.py#L172-L191
train
bitprophet/ssh
ssh/hostkeys.py
HostKeys.lookup
def lookup(self, hostname): """ Find a hostkey entry for a given hostname or IP. If no entry is found, C{None} is returned. Otherwise a dictionary of keytype to key is returned. The keytype will be either C{"ssh-rsa"} or C{"ssh-dss"}. @param hostname: the hostname (or IP) to lookup @type hostname: str @return: keys associated with this host (or C{None}) @rtype: dict(str, L{PKey}) """ class SubDict (UserDict.DictMixin): def __init__(self, hostname, entries, hostkeys): self._hostname = hostname self._entries = entries self._hostkeys = hostkeys def __getitem__(self, key): for e in self._entries: if e.key.get_name() == key: return e.key raise KeyError(key) def __setitem__(self, key, val): for e in self._entries: if e.key is None: continue if e.key.get_name() == key: # replace e.key = val break else: # add a new one e = HostKeyEntry([hostname], val) self._entries.append(e) self._hostkeys._entries.append(e) def keys(self): return [e.key.get_name() for e in self._entries if e.key is not None] entries = [] for e in self._entries: for h in e.hostnames: if (h.startswith('|1|') and (self.hash_host(hostname, h) == h)) or (h == hostname): entries.append(e) if len(entries) == 0: return None return SubDict(hostname, entries, self)
python
def lookup(self, hostname): """ Find a hostkey entry for a given hostname or IP. If no entry is found, C{None} is returned. Otherwise a dictionary of keytype to key is returned. The keytype will be either C{"ssh-rsa"} or C{"ssh-dss"}. @param hostname: the hostname (or IP) to lookup @type hostname: str @return: keys associated with this host (or C{None}) @rtype: dict(str, L{PKey}) """ class SubDict (UserDict.DictMixin): def __init__(self, hostname, entries, hostkeys): self._hostname = hostname self._entries = entries self._hostkeys = hostkeys def __getitem__(self, key): for e in self._entries: if e.key.get_name() == key: return e.key raise KeyError(key) def __setitem__(self, key, val): for e in self._entries: if e.key is None: continue if e.key.get_name() == key: # replace e.key = val break else: # add a new one e = HostKeyEntry([hostname], val) self._entries.append(e) self._hostkeys._entries.append(e) def keys(self): return [e.key.get_name() for e in self._entries if e.key is not None] entries = [] for e in self._entries: for h in e.hostnames: if (h.startswith('|1|') and (self.hash_host(hostname, h) == h)) or (h == hostname): entries.append(e) if len(entries) == 0: return None return SubDict(hostname, entries, self)
[ "def", "lookup", "(", "self", ",", "hostname", ")", ":", "class", "SubDict", "(", "UserDict", ".", "DictMixin", ")", ":", "def", "__init__", "(", "self", ",", "hostname", ",", "entries", ",", "hostkeys", ")", ":", "self", ".", "_hostname", "=", "hostname", "self", ".", "_entries", "=", "entries", "self", ".", "_hostkeys", "=", "hostkeys", "def", "__getitem__", "(", "self", ",", "key", ")", ":", "for", "e", "in", "self", ".", "_entries", ":", "if", "e", ".", "key", ".", "get_name", "(", ")", "==", "key", ":", "return", "e", ".", "key", "raise", "KeyError", "(", "key", ")", "def", "__setitem__", "(", "self", ",", "key", ",", "val", ")", ":", "for", "e", "in", "self", ".", "_entries", ":", "if", "e", ".", "key", "is", "None", ":", "continue", "if", "e", ".", "key", ".", "get_name", "(", ")", "==", "key", ":", "# replace", "e", ".", "key", "=", "val", "break", "else", ":", "# add a new one", "e", "=", "HostKeyEntry", "(", "[", "hostname", "]", ",", "val", ")", "self", ".", "_entries", ".", "append", "(", "e", ")", "self", ".", "_hostkeys", ".", "_entries", ".", "append", "(", "e", ")", "def", "keys", "(", "self", ")", ":", "return", "[", "e", ".", "key", ".", "get_name", "(", ")", "for", "e", "in", "self", ".", "_entries", "if", "e", ".", "key", "is", "not", "None", "]", "entries", "=", "[", "]", "for", "e", "in", "self", ".", "_entries", ":", "for", "h", "in", "e", ".", "hostnames", ":", "if", "(", "h", ".", "startswith", "(", "'|1|'", ")", "and", "(", "self", ".", "hash_host", "(", "hostname", ",", "h", ")", "==", "h", ")", ")", "or", "(", "h", "==", "hostname", ")", ":", "entries", ".", "append", "(", "e", ")", "if", "len", "(", "entries", ")", "==", "0", ":", "return", "None", "return", "SubDict", "(", "hostname", ",", "entries", ",", "self", ")" ]
Find a hostkey entry for a given hostname or IP. If no entry is found, C{None} is returned. Otherwise a dictionary of keytype to key is returned. The keytype will be either C{"ssh-rsa"} or C{"ssh-dss"}. @param hostname: the hostname (or IP) to lookup @type hostname: str @return: keys associated with this host (or C{None}) @rtype: dict(str, L{PKey})
[ "Find", "a", "hostkey", "entry", "for", "a", "given", "hostname", "or", "IP", ".", "If", "no", "entry", "is", "found", "C", "{", "None", "}", "is", "returned", ".", "Otherwise", "a", "dictionary", "of", "keytype", "to", "key", "is", "returned", ".", "The", "keytype", "will", "be", "either", "C", "{", "ssh", "-", "rsa", "}", "or", "C", "{", "ssh", "-", "dss", "}", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/hostkeys.py#L193-L240
train
bitprophet/ssh
ssh/hostkeys.py
HostKeys.check
def check(self, hostname, key): """ Return True if the given key is associated with the given hostname in this dictionary. @param hostname: hostname (or IP) of the SSH server @type hostname: str @param key: the key to check @type key: L{PKey} @return: C{True} if the key is associated with the hostname; C{False} if not @rtype: bool """ k = self.lookup(hostname) if k is None: return False host_key = k.get(key.get_name(), None) if host_key is None: return False return str(host_key) == str(key)
python
def check(self, hostname, key): """ Return True if the given key is associated with the given hostname in this dictionary. @param hostname: hostname (or IP) of the SSH server @type hostname: str @param key: the key to check @type key: L{PKey} @return: C{True} if the key is associated with the hostname; C{False} if not @rtype: bool """ k = self.lookup(hostname) if k is None: return False host_key = k.get(key.get_name(), None) if host_key is None: return False return str(host_key) == str(key)
[ "def", "check", "(", "self", ",", "hostname", ",", "key", ")", ":", "k", "=", "self", ".", "lookup", "(", "hostname", ")", "if", "k", "is", "None", ":", "return", "False", "host_key", "=", "k", ".", "get", "(", "key", ".", "get_name", "(", ")", ",", "None", ")", "if", "host_key", "is", "None", ":", "return", "False", "return", "str", "(", "host_key", ")", "==", "str", "(", "key", ")" ]
Return True if the given key is associated with the given hostname in this dictionary. @param hostname: hostname (or IP) of the SSH server @type hostname: str @param key: the key to check @type key: L{PKey} @return: C{True} if the key is associated with the hostname; C{False} if not @rtype: bool
[ "Return", "True", "if", "the", "given", "key", "is", "associated", "with", "the", "given", "hostname", "in", "this", "dictionary", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/hostkeys.py#L242-L261
train
bitprophet/ssh
ssh/hostkeys.py
HostKeys.hash_host
def hash_host(hostname, salt=None): """ Return a "hashed" form of the hostname, as used by openssh when storing hashed hostnames in the known_hosts file. @param hostname: the hostname to hash @type hostname: str @param salt: optional salt to use when hashing (must be 20 bytes long) @type salt: str @return: the hashed hostname @rtype: str """ if salt is None: salt = rng.read(SHA.digest_size) else: if salt.startswith('|1|'): salt = salt.split('|')[2] salt = base64.decodestring(salt) assert len(salt) == SHA.digest_size hmac = HMAC.HMAC(salt, hostname, SHA).digest() hostkey = '|1|%s|%s' % (base64.encodestring(salt), base64.encodestring(hmac)) return hostkey.replace('\n', '')
python
def hash_host(hostname, salt=None): """ Return a "hashed" form of the hostname, as used by openssh when storing hashed hostnames in the known_hosts file. @param hostname: the hostname to hash @type hostname: str @param salt: optional salt to use when hashing (must be 20 bytes long) @type salt: str @return: the hashed hostname @rtype: str """ if salt is None: salt = rng.read(SHA.digest_size) else: if salt.startswith('|1|'): salt = salt.split('|')[2] salt = base64.decodestring(salt) assert len(salt) == SHA.digest_size hmac = HMAC.HMAC(salt, hostname, SHA).digest() hostkey = '|1|%s|%s' % (base64.encodestring(salt), base64.encodestring(hmac)) return hostkey.replace('\n', '')
[ "def", "hash_host", "(", "hostname", ",", "salt", "=", "None", ")", ":", "if", "salt", "is", "None", ":", "salt", "=", "rng", ".", "read", "(", "SHA", ".", "digest_size", ")", "else", ":", "if", "salt", ".", "startswith", "(", "'|1|'", ")", ":", "salt", "=", "salt", ".", "split", "(", "'|'", ")", "[", "2", "]", "salt", "=", "base64", ".", "decodestring", "(", "salt", ")", "assert", "len", "(", "salt", ")", "==", "SHA", ".", "digest_size", "hmac", "=", "HMAC", ".", "HMAC", "(", "salt", ",", "hostname", ",", "SHA", ")", ".", "digest", "(", ")", "hostkey", "=", "'|1|%s|%s'", "%", "(", "base64", ".", "encodestring", "(", "salt", ")", ",", "base64", ".", "encodestring", "(", "hmac", ")", ")", "return", "hostkey", ".", "replace", "(", "'\\n'", ",", "''", ")" ]
Return a "hashed" form of the hostname, as used by openssh when storing hashed hostnames in the known_hosts file. @param hostname: the hostname to hash @type hostname: str @param salt: optional salt to use when hashing (must be 20 bytes long) @type salt: str @return: the hashed hostname @rtype: str
[ "Return", "a", "hashed", "form", "of", "the", "hostname", "as", "used", "by", "openssh", "when", "storing", "hashed", "hostnames", "in", "the", "known_hosts", "file", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/hostkeys.py#L305-L326
train
bitprophet/ssh
ssh/util.py
inflate_long
def inflate_long(s, always_positive=False): "turns a normalized byte string into a long-int (adapted from Crypto.Util.number)" out = 0L negative = 0 if not always_positive and (len(s) > 0) and (ord(s[0]) >= 0x80): negative = 1 if len(s) % 4: filler = '\x00' if negative: filler = '\xff' s = filler * (4 - len(s) % 4) + s for i in range(0, len(s), 4): out = (out << 32) + struct.unpack('>I', s[i:i+4])[0] if negative: out -= (1L << (8 * len(s))) return out
python
def inflate_long(s, always_positive=False): "turns a normalized byte string into a long-int (adapted from Crypto.Util.number)" out = 0L negative = 0 if not always_positive and (len(s) > 0) and (ord(s[0]) >= 0x80): negative = 1 if len(s) % 4: filler = '\x00' if negative: filler = '\xff' s = filler * (4 - len(s) % 4) + s for i in range(0, len(s), 4): out = (out << 32) + struct.unpack('>I', s[i:i+4])[0] if negative: out -= (1L << (8 * len(s))) return out
[ "def", "inflate_long", "(", "s", ",", "always_positive", "=", "False", ")", ":", "out", "=", "0L", "negative", "=", "0", "if", "not", "always_positive", "and", "(", "len", "(", "s", ")", ">", "0", ")", "and", "(", "ord", "(", "s", "[", "0", "]", ")", ">=", "0x80", ")", ":", "negative", "=", "1", "if", "len", "(", "s", ")", "%", "4", ":", "filler", "=", "'\\x00'", "if", "negative", ":", "filler", "=", "'\\xff'", "s", "=", "filler", "*", "(", "4", "-", "len", "(", "s", ")", "%", "4", ")", "+", "s", "for", "i", "in", "range", "(", "0", ",", "len", "(", "s", ")", ",", "4", ")", ":", "out", "=", "(", "out", "<<", "32", ")", "+", "struct", ".", "unpack", "(", "'>I'", ",", "s", "[", "i", ":", "i", "+", "4", "]", ")", "[", "0", "]", "if", "negative", ":", "out", "-=", "(", "1L", "<<", "(", "8", "*", "len", "(", "s", ")", ")", ")", "return", "out" ]
turns a normalized byte string into a long-int (adapted from Crypto.Util.number)
[ "turns", "a", "normalized", "byte", "string", "into", "a", "long", "-", "int", "(", "adapted", "from", "Crypto", ".", "Util", ".", "number", ")" ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/util.py#L49-L64
train
bitprophet/ssh
ssh/util.py
deflate_long
def deflate_long(n, add_sign_padding=True): "turns a long-int into a normalized byte string (adapted from Crypto.Util.number)" # after much testing, this algorithm was deemed to be the fastest s = '' n = long(n) while (n != 0) and (n != -1): s = struct.pack('>I', n & 0xffffffffL) + s n = n >> 32 # strip off leading zeros, FFs for i in enumerate(s): if (n == 0) and (i[1] != '\000'): break if (n == -1) and (i[1] != '\xff'): break else: # degenerate case, n was either 0 or -1 i = (0,) if n == 0: s = '\000' else: s = '\xff' s = s[i[0]:] if add_sign_padding: if (n == 0) and (ord(s[0]) >= 0x80): s = '\x00' + s if (n == -1) and (ord(s[0]) < 0x80): s = '\xff' + s return s
python
def deflate_long(n, add_sign_padding=True): "turns a long-int into a normalized byte string (adapted from Crypto.Util.number)" # after much testing, this algorithm was deemed to be the fastest s = '' n = long(n) while (n != 0) and (n != -1): s = struct.pack('>I', n & 0xffffffffL) + s n = n >> 32 # strip off leading zeros, FFs for i in enumerate(s): if (n == 0) and (i[1] != '\000'): break if (n == -1) and (i[1] != '\xff'): break else: # degenerate case, n was either 0 or -1 i = (0,) if n == 0: s = '\000' else: s = '\xff' s = s[i[0]:] if add_sign_padding: if (n == 0) and (ord(s[0]) >= 0x80): s = '\x00' + s if (n == -1) and (ord(s[0]) < 0x80): s = '\xff' + s return s
[ "def", "deflate_long", "(", "n", ",", "add_sign_padding", "=", "True", ")", ":", "# after much testing, this algorithm was deemed to be the fastest", "s", "=", "''", "n", "=", "long", "(", "n", ")", "while", "(", "n", "!=", "0", ")", "and", "(", "n", "!=", "-", "1", ")", ":", "s", "=", "struct", ".", "pack", "(", "'>I'", ",", "n", "&", "0xffffffffL", ")", "+", "s", "n", "=", "n", ">>", "32", "# strip off leading zeros, FFs", "for", "i", "in", "enumerate", "(", "s", ")", ":", "if", "(", "n", "==", "0", ")", "and", "(", "i", "[", "1", "]", "!=", "'\\000'", ")", ":", "break", "if", "(", "n", "==", "-", "1", ")", "and", "(", "i", "[", "1", "]", "!=", "'\\xff'", ")", ":", "break", "else", ":", "# degenerate case, n was either 0 or -1", "i", "=", "(", "0", ",", ")", "if", "n", "==", "0", ":", "s", "=", "'\\000'", "else", ":", "s", "=", "'\\xff'", "s", "=", "s", "[", "i", "[", "0", "]", ":", "]", "if", "add_sign_padding", ":", "if", "(", "n", "==", "0", ")", "and", "(", "ord", "(", "s", "[", "0", "]", ")", ">=", "0x80", ")", ":", "s", "=", "'\\x00'", "+", "s", "if", "(", "n", "==", "-", "1", ")", "and", "(", "ord", "(", "s", "[", "0", "]", ")", "<", "0x80", ")", ":", "s", "=", "'\\xff'", "+", "s", "return", "s" ]
turns a long-int into a normalized byte string (adapted from Crypto.Util.number)
[ "turns", "a", "long", "-", "int", "into", "a", "normalized", "byte", "string", "(", "adapted", "from", "Crypto", ".", "Util", ".", "number", ")" ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/util.py#L66-L93
train
bitprophet/ssh
ssh/util.py
generate_key_bytes
def generate_key_bytes(hashclass, salt, key, nbytes): """ Given a password, passphrase, or other human-source key, scramble it through a secure hash into some keyworthy bytes. This specific algorithm is used for encrypting/decrypting private key files. @param hashclass: class from L{Crypto.Hash} that can be used as a secure hashing function (like C{MD5} or C{SHA}). @type hashclass: L{Crypto.Hash} @param salt: data to salt the hash with. @type salt: string @param key: human-entered password or passphrase. @type key: string @param nbytes: number of bytes to generate. @type nbytes: int @return: key data @rtype: string """ keydata = '' digest = '' if len(salt) > 8: salt = salt[:8] while nbytes > 0: hash_obj = hashclass.new() if len(digest) > 0: hash_obj.update(digest) hash_obj.update(key) hash_obj.update(salt) digest = hash_obj.digest() size = min(nbytes, len(digest)) keydata += digest[:size] nbytes -= size return keydata
python
def generate_key_bytes(hashclass, salt, key, nbytes): """ Given a password, passphrase, or other human-source key, scramble it through a secure hash into some keyworthy bytes. This specific algorithm is used for encrypting/decrypting private key files. @param hashclass: class from L{Crypto.Hash} that can be used as a secure hashing function (like C{MD5} or C{SHA}). @type hashclass: L{Crypto.Hash} @param salt: data to salt the hash with. @type salt: string @param key: human-entered password or passphrase. @type key: string @param nbytes: number of bytes to generate. @type nbytes: int @return: key data @rtype: string """ keydata = '' digest = '' if len(salt) > 8: salt = salt[:8] while nbytes > 0: hash_obj = hashclass.new() if len(digest) > 0: hash_obj.update(digest) hash_obj.update(key) hash_obj.update(salt) digest = hash_obj.digest() size = min(nbytes, len(digest)) keydata += digest[:size] nbytes -= size return keydata
[ "def", "generate_key_bytes", "(", "hashclass", ",", "salt", ",", "key", ",", "nbytes", ")", ":", "keydata", "=", "''", "digest", "=", "''", "if", "len", "(", "salt", ")", ">", "8", ":", "salt", "=", "salt", "[", ":", "8", "]", "while", "nbytes", ">", "0", ":", "hash_obj", "=", "hashclass", ".", "new", "(", ")", "if", "len", "(", "digest", ")", ">", "0", ":", "hash_obj", ".", "update", "(", "digest", ")", "hash_obj", ".", "update", "(", "key", ")", "hash_obj", ".", "update", "(", "salt", ")", "digest", "=", "hash_obj", ".", "digest", "(", ")", "size", "=", "min", "(", "nbytes", ",", "len", "(", "digest", ")", ")", "keydata", "+=", "digest", "[", ":", "size", "]", "nbytes", "-=", "size", "return", "keydata" ]
Given a password, passphrase, or other human-source key, scramble it through a secure hash into some keyworthy bytes. This specific algorithm is used for encrypting/decrypting private key files. @param hashclass: class from L{Crypto.Hash} that can be used as a secure hashing function (like C{MD5} or C{SHA}). @type hashclass: L{Crypto.Hash} @param salt: data to salt the hash with. @type salt: string @param key: human-entered password or passphrase. @type key: string @param nbytes: number of bytes to generate. @type nbytes: int @return: key data @rtype: string
[ "Given", "a", "password", "passphrase", "or", "other", "human", "-", "source", "key", "scramble", "it", "through", "a", "secure", "hash", "into", "some", "keyworthy", "bytes", ".", "This", "specific", "algorithm", "is", "used", "for", "encrypting", "/", "decrypting", "private", "key", "files", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/util.py#L151-L183
train
bitprophet/ssh
ssh/util.py
retry_on_signal
def retry_on_signal(function): """Retries function until it doesn't raise an EINTR error""" while True: try: return function() except EnvironmentError, e: if e.errno != errno.EINTR: raise
python
def retry_on_signal(function): """Retries function until it doesn't raise an EINTR error""" while True: try: return function() except EnvironmentError, e: if e.errno != errno.EINTR: raise
[ "def", "retry_on_signal", "(", "function", ")", ":", "while", "True", ":", "try", ":", "return", "function", "(", ")", "except", "EnvironmentError", ",", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "EINTR", ":", "raise" ]
Retries function until it doesn't raise an EINTR error
[ "Retries", "function", "until", "it", "doesn", "t", "raise", "an", "EINTR", "error" ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/util.py#L274-L281
train
bitprophet/ssh
ssh/rsakey.py
RSAKey.generate
def generate(bits, progress_func=None): """ Generate a new private RSA key. This factory function can be used to generate a new host key or authentication key. @param bits: number of bits the generated key should be. @type bits: int @param progress_func: an optional function to call at key points in key generation (used by C{pyCrypto.PublicKey}). @type progress_func: function @return: new private key @rtype: L{RSAKey} """ rsa = RSA.generate(bits, rng.read, progress_func) key = RSAKey(vals=(rsa.e, rsa.n)) key.d = rsa.d key.p = rsa.p key.q = rsa.q return key
python
def generate(bits, progress_func=None): """ Generate a new private RSA key. This factory function can be used to generate a new host key or authentication key. @param bits: number of bits the generated key should be. @type bits: int @param progress_func: an optional function to call at key points in key generation (used by C{pyCrypto.PublicKey}). @type progress_func: function @return: new private key @rtype: L{RSAKey} """ rsa = RSA.generate(bits, rng.read, progress_func) key = RSAKey(vals=(rsa.e, rsa.n)) key.d = rsa.d key.p = rsa.p key.q = rsa.q return key
[ "def", "generate", "(", "bits", ",", "progress_func", "=", "None", ")", ":", "rsa", "=", "RSA", ".", "generate", "(", "bits", ",", "rng", ".", "read", ",", "progress_func", ")", "key", "=", "RSAKey", "(", "vals", "=", "(", "rsa", ".", "e", ",", "rsa", ".", "n", ")", ")", "key", ".", "d", "=", "rsa", ".", "d", "key", ".", "p", "=", "rsa", ".", "p", "key", ".", "q", "=", "rsa", ".", "q", "return", "key" ]
Generate a new private RSA key. This factory function can be used to generate a new host key or authentication key. @param bits: number of bits the generated key should be. @type bits: int @param progress_func: an optional function to call at key points in key generation (used by C{pyCrypto.PublicKey}). @type progress_func: function @return: new private key @rtype: L{RSAKey}
[ "Generate", "a", "new", "private", "RSA", "key", ".", "This", "factory", "function", "can", "be", "used", "to", "generate", "a", "new", "host", "key", "or", "authentication", "key", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/rsakey.py#L127-L145
train
bitprophet/ssh
ssh/rsakey.py
RSAKey._pkcs1imify
def _pkcs1imify(self, data): """ turn a 20-byte SHA1 hash into a blob of data as large as the key's N, using PKCS1's \"emsa-pkcs1-v1_5\" encoding. totally bizarre. """ SHA1_DIGESTINFO = '\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14' size = len(util.deflate_long(self.n, 0)) filler = '\xff' * (size - len(SHA1_DIGESTINFO) - len(data) - 3) return '\x00\x01' + filler + '\x00' + SHA1_DIGESTINFO + data
python
def _pkcs1imify(self, data): """ turn a 20-byte SHA1 hash into a blob of data as large as the key's N, using PKCS1's \"emsa-pkcs1-v1_5\" encoding. totally bizarre. """ SHA1_DIGESTINFO = '\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14' size = len(util.deflate_long(self.n, 0)) filler = '\xff' * (size - len(SHA1_DIGESTINFO) - len(data) - 3) return '\x00\x01' + filler + '\x00' + SHA1_DIGESTINFO + data
[ "def", "_pkcs1imify", "(", "self", ",", "data", ")", ":", "SHA1_DIGESTINFO", "=", "'\\x30\\x21\\x30\\x09\\x06\\x05\\x2b\\x0e\\x03\\x02\\x1a\\x05\\x00\\x04\\x14'", "size", "=", "len", "(", "util", ".", "deflate_long", "(", "self", ".", "n", ",", "0", ")", ")", "filler", "=", "'\\xff'", "*", "(", "size", "-", "len", "(", "SHA1_DIGESTINFO", ")", "-", "len", "(", "data", ")", "-", "3", ")", "return", "'\\x00\\x01'", "+", "filler", "+", "'\\x00'", "+", "SHA1_DIGESTINFO", "+", "data" ]
turn a 20-byte SHA1 hash into a blob of data as large as the key's N, using PKCS1's \"emsa-pkcs1-v1_5\" encoding. totally bizarre.
[ "turn", "a", "20", "-", "byte", "SHA1", "hash", "into", "a", "blob", "of", "data", "as", "large", "as", "the", "key", "s", "N", "using", "PKCS1", "s", "\\", "emsa", "-", "pkcs1", "-", "v1_5", "\\", "encoding", ".", "totally", "bizarre", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/rsakey.py#L152-L160
train
bitprophet/ssh
ssh/dsskey.py
DSSKey.generate
def generate(bits=1024, progress_func=None): """ Generate a new private DSS key. This factory function can be used to generate a new host key or authentication key. @param bits: number of bits the generated key should be. @type bits: int @param progress_func: an optional function to call at key points in key generation (used by C{pyCrypto.PublicKey}). @type progress_func: function @return: new private key @rtype: L{DSSKey} """ dsa = DSA.generate(bits, rng.read, progress_func) key = DSSKey(vals=(dsa.p, dsa.q, dsa.g, dsa.y)) key.x = dsa.x return key
python
def generate(bits=1024, progress_func=None): """ Generate a new private DSS key. This factory function can be used to generate a new host key or authentication key. @param bits: number of bits the generated key should be. @type bits: int @param progress_func: an optional function to call at key points in key generation (used by C{pyCrypto.PublicKey}). @type progress_func: function @return: new private key @rtype: L{DSSKey} """ dsa = DSA.generate(bits, rng.read, progress_func) key = DSSKey(vals=(dsa.p, dsa.q, dsa.g, dsa.y)) key.x = dsa.x return key
[ "def", "generate", "(", "bits", "=", "1024", ",", "progress_func", "=", "None", ")", ":", "dsa", "=", "DSA", ".", "generate", "(", "bits", ",", "rng", ".", "read", ",", "progress_func", ")", "key", "=", "DSSKey", "(", "vals", "=", "(", "dsa", ".", "p", ",", "dsa", ".", "q", ",", "dsa", ".", "g", ",", "dsa", ".", "y", ")", ")", "key", ".", "x", "=", "dsa", ".", "x", "return", "key" ]
Generate a new private DSS key. This factory function can be used to generate a new host key or authentication key. @param bits: number of bits the generated key should be. @type bits: int @param progress_func: an optional function to call at key points in key generation (used by C{pyCrypto.PublicKey}). @type progress_func: function @return: new private key @rtype: L{DSSKey}
[ "Generate", "a", "new", "private", "DSS", "key", ".", "This", "factory", "function", "can", "be", "used", "to", "generate", "a", "new", "host", "key", "or", "authentication", "key", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/dsskey.py#L151-L167
train
bitprophet/ssh
ssh/config.py
SSHConfig.parse
def parse(self, file_obj): """ Read an OpenSSH config from the given file object. @param file_obj: a file-like object to read the config file from @type file_obj: file """ configs = [self._config[0]] for line in file_obj: line = line.rstrip('\n').lstrip() if (line == '') or (line[0] == '#'): continue if '=' in line: key, value = line.split('=', 1) key = key.strip().lower() else: # find first whitespace, and split there i = 0 while (i < len(line)) and not line[i].isspace(): i += 1 if i == len(line): raise Exception('Unparsable line: %r' % line) key = line[:i].lower() value = line[i:].lstrip() if key == 'host': del configs[:] # the value may be multiple hosts, space-delimited for host in value.split(): # do we have a pre-existing host config to append to? matches = [c for c in self._config if c['host'] == host] if len(matches) > 0: configs.append(matches[0]) else: config = { 'host': host } self._config.append(config) configs.append(config) else: for config in configs: config[key] = value
python
def parse(self, file_obj): """ Read an OpenSSH config from the given file object. @param file_obj: a file-like object to read the config file from @type file_obj: file """ configs = [self._config[0]] for line in file_obj: line = line.rstrip('\n').lstrip() if (line == '') or (line[0] == '#'): continue if '=' in line: key, value = line.split('=', 1) key = key.strip().lower() else: # find first whitespace, and split there i = 0 while (i < len(line)) and not line[i].isspace(): i += 1 if i == len(line): raise Exception('Unparsable line: %r' % line) key = line[:i].lower() value = line[i:].lstrip() if key == 'host': del configs[:] # the value may be multiple hosts, space-delimited for host in value.split(): # do we have a pre-existing host config to append to? matches = [c for c in self._config if c['host'] == host] if len(matches) > 0: configs.append(matches[0]) else: config = { 'host': host } self._config.append(config) configs.append(config) else: for config in configs: config[key] = value
[ "def", "parse", "(", "self", ",", "file_obj", ")", ":", "configs", "=", "[", "self", ".", "_config", "[", "0", "]", "]", "for", "line", "in", "file_obj", ":", "line", "=", "line", ".", "rstrip", "(", "'\\n'", ")", ".", "lstrip", "(", ")", "if", "(", "line", "==", "''", ")", "or", "(", "line", "[", "0", "]", "==", "'#'", ")", ":", "continue", "if", "'='", "in", "line", ":", "key", ",", "value", "=", "line", ".", "split", "(", "'='", ",", "1", ")", "key", "=", "key", ".", "strip", "(", ")", ".", "lower", "(", ")", "else", ":", "# find first whitespace, and split there", "i", "=", "0", "while", "(", "i", "<", "len", "(", "line", ")", ")", "and", "not", "line", "[", "i", "]", ".", "isspace", "(", ")", ":", "i", "+=", "1", "if", "i", "==", "len", "(", "line", ")", ":", "raise", "Exception", "(", "'Unparsable line: %r'", "%", "line", ")", "key", "=", "line", "[", ":", "i", "]", ".", "lower", "(", ")", "value", "=", "line", "[", "i", ":", "]", ".", "lstrip", "(", ")", "if", "key", "==", "'host'", ":", "del", "configs", "[", ":", "]", "# the value may be multiple hosts, space-delimited", "for", "host", "in", "value", ".", "split", "(", ")", ":", "# do we have a pre-existing host config to append to?", "matches", "=", "[", "c", "for", "c", "in", "self", ".", "_config", "if", "c", "[", "'host'", "]", "==", "host", "]", "if", "len", "(", "matches", ")", ">", "0", ":", "configs", ".", "append", "(", "matches", "[", "0", "]", ")", "else", ":", "config", "=", "{", "'host'", ":", "host", "}", "self", ".", "_config", ".", "append", "(", "config", ")", "configs", ".", "append", "(", "config", ")", "else", ":", "for", "config", "in", "configs", ":", "config", "[", "key", "]", "=", "value" ]
Read an OpenSSH config from the given file object. @param file_obj: a file-like object to read the config file from @type file_obj: file
[ "Read", "an", "OpenSSH", "config", "from", "the", "given", "file", "object", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/config.py#L46-L85
train
bitprophet/ssh
ssh/config.py
SSHConfig.lookup
def lookup(self, hostname): """ Return a dict of config options for a given hostname. The host-matching rules of OpenSSH's C{ssh_config} man page are used, which means that all configuration options from matching host specifications are merged, with more specific hostmasks taking precedence. In other words, if C{"Port"} is set under C{"Host *"} and also C{"Host *.example.com"}, and the lookup is for C{"ssh.example.com"}, then the port entry for C{"Host *.example.com"} will win out. The keys in the returned dict are all normalized to lowercase (look for C{"port"}, not C{"Port"}. No other processing is done to the keys or values. @param hostname: the hostname to lookup @type hostname: str """ matches = [x for x in self._config if fnmatch.fnmatch(hostname, x['host'])] # Move * to the end _star = matches.pop(0) matches.append(_star) ret = {} for m in matches: for k,v in m.iteritems(): if not k in ret: ret[k] = v ret = self._expand_variables(ret, hostname) del ret['host'] return ret
python
def lookup(self, hostname): """ Return a dict of config options for a given hostname. The host-matching rules of OpenSSH's C{ssh_config} man page are used, which means that all configuration options from matching host specifications are merged, with more specific hostmasks taking precedence. In other words, if C{"Port"} is set under C{"Host *"} and also C{"Host *.example.com"}, and the lookup is for C{"ssh.example.com"}, then the port entry for C{"Host *.example.com"} will win out. The keys in the returned dict are all normalized to lowercase (look for C{"port"}, not C{"Port"}. No other processing is done to the keys or values. @param hostname: the hostname to lookup @type hostname: str """ matches = [x for x in self._config if fnmatch.fnmatch(hostname, x['host'])] # Move * to the end _star = matches.pop(0) matches.append(_star) ret = {} for m in matches: for k,v in m.iteritems(): if not k in ret: ret[k] = v ret = self._expand_variables(ret, hostname) del ret['host'] return ret
[ "def", "lookup", "(", "self", ",", "hostname", ")", ":", "matches", "=", "[", "x", "for", "x", "in", "self", ".", "_config", "if", "fnmatch", ".", "fnmatch", "(", "hostname", ",", "x", "[", "'host'", "]", ")", "]", "# Move * to the end", "_star", "=", "matches", ".", "pop", "(", "0", ")", "matches", ".", "append", "(", "_star", ")", "ret", "=", "{", "}", "for", "m", "in", "matches", ":", "for", "k", ",", "v", "in", "m", ".", "iteritems", "(", ")", ":", "if", "not", "k", "in", "ret", ":", "ret", "[", "k", "]", "=", "v", "ret", "=", "self", ".", "_expand_variables", "(", "ret", ",", "hostname", ")", "del", "ret", "[", "'host'", "]", "return", "ret" ]
Return a dict of config options for a given hostname. The host-matching rules of OpenSSH's C{ssh_config} man page are used, which means that all configuration options from matching host specifications are merged, with more specific hostmasks taking precedence. In other words, if C{"Port"} is set under C{"Host *"} and also C{"Host *.example.com"}, and the lookup is for C{"ssh.example.com"}, then the port entry for C{"Host *.example.com"} will win out. The keys in the returned dict are all normalized to lowercase (look for C{"port"}, not C{"Port"}. No other processing is done to the keys or values. @param hostname: the hostname to lookup @type hostname: str
[ "Return", "a", "dict", "of", "config", "options", "for", "a", "given", "hostname", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/config.py#L87-L117
train
bitprophet/ssh
ssh/config.py
SSHConfig._expand_variables
def _expand_variables(self, config, hostname ): """ Return a dict of config options with expanded substitutions for a given hostname. Please refer to man ssh_config(5) for the parameters that are replaced. @param config: the config for the hostname @type hostname: dict @param hostname: the hostname that the config belongs to @type hostname: str """ if 'hostname' in config: config['hostname'] = config['hostname'].replace('%h',hostname) else: config['hostname'] = hostname if 'port' in config: port = config['port'] else: port = SSH_PORT user = os.getenv('USER') if 'user' in config: remoteuser = config['user'] else: remoteuser = user host = socket.gethostname().split('.')[0] fqdn = socket.getfqdn() homedir = os.path.expanduser('~') replacements = {'controlpath' : [ ('%h', config['hostname']), ('%l', fqdn), ('%L', host), ('%n', hostname), ('%p', port), ('%r', remoteuser), ('%u', user) ], 'identityfile' : [ ('~', homedir), ('%d', homedir), ('%h', config['hostname']), ('%l', fqdn), ('%u', user), ('%r', remoteuser) ] } for k in config: if k in replacements: for find, replace in replacements[k]: config[k] = config[k].replace(find, str(replace)) return config
python
def _expand_variables(self, config, hostname ): """ Return a dict of config options with expanded substitutions for a given hostname. Please refer to man ssh_config(5) for the parameters that are replaced. @param config: the config for the hostname @type hostname: dict @param hostname: the hostname that the config belongs to @type hostname: str """ if 'hostname' in config: config['hostname'] = config['hostname'].replace('%h',hostname) else: config['hostname'] = hostname if 'port' in config: port = config['port'] else: port = SSH_PORT user = os.getenv('USER') if 'user' in config: remoteuser = config['user'] else: remoteuser = user host = socket.gethostname().split('.')[0] fqdn = socket.getfqdn() homedir = os.path.expanduser('~') replacements = {'controlpath' : [ ('%h', config['hostname']), ('%l', fqdn), ('%L', host), ('%n', hostname), ('%p', port), ('%r', remoteuser), ('%u', user) ], 'identityfile' : [ ('~', homedir), ('%d', homedir), ('%h', config['hostname']), ('%l', fqdn), ('%u', user), ('%r', remoteuser) ] } for k in config: if k in replacements: for find, replace in replacements[k]: config[k] = config[k].replace(find, str(replace)) return config
[ "def", "_expand_variables", "(", "self", ",", "config", ",", "hostname", ")", ":", "if", "'hostname'", "in", "config", ":", "config", "[", "'hostname'", "]", "=", "config", "[", "'hostname'", "]", ".", "replace", "(", "'%h'", ",", "hostname", ")", "else", ":", "config", "[", "'hostname'", "]", "=", "hostname", "if", "'port'", "in", "config", ":", "port", "=", "config", "[", "'port'", "]", "else", ":", "port", "=", "SSH_PORT", "user", "=", "os", ".", "getenv", "(", "'USER'", ")", "if", "'user'", "in", "config", ":", "remoteuser", "=", "config", "[", "'user'", "]", "else", ":", "remoteuser", "=", "user", "host", "=", "socket", ".", "gethostname", "(", ")", ".", "split", "(", "'.'", ")", "[", "0", "]", "fqdn", "=", "socket", ".", "getfqdn", "(", ")", "homedir", "=", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", "replacements", "=", "{", "'controlpath'", ":", "[", "(", "'%h'", ",", "config", "[", "'hostname'", "]", ")", ",", "(", "'%l'", ",", "fqdn", ")", ",", "(", "'%L'", ",", "host", ")", ",", "(", "'%n'", ",", "hostname", ")", ",", "(", "'%p'", ",", "port", ")", ",", "(", "'%r'", ",", "remoteuser", ")", ",", "(", "'%u'", ",", "user", ")", "]", ",", "'identityfile'", ":", "[", "(", "'~'", ",", "homedir", ")", ",", "(", "'%d'", ",", "homedir", ")", ",", "(", "'%h'", ",", "config", "[", "'hostname'", "]", ")", ",", "(", "'%l'", ",", "fqdn", ")", ",", "(", "'%u'", ",", "user", ")", ",", "(", "'%r'", ",", "remoteuser", ")", "]", "}", "for", "k", "in", "config", ":", "if", "k", "in", "replacements", ":", "for", "find", ",", "replace", "in", "replacements", "[", "k", "]", ":", "config", "[", "k", "]", "=", "config", "[", "k", "]", ".", "replace", "(", "find", ",", "str", "(", "replace", ")", ")", "return", "config" ]
Return a dict of config options with expanded substitutions for a given hostname. Please refer to man ssh_config(5) for the parameters that are replaced. @param config: the config for the hostname @type hostname: dict @param hostname: the hostname that the config belongs to @type hostname: str
[ "Return", "a", "dict", "of", "config", "options", "with", "expanded", "substitutions", "for", "a", "given", "hostname", "." ]
e8bdad4c82a50158a749233dca58c29e47c60b76
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/config.py#L119-L176
train
Spirent/py-stcrestclient
stcrestclient/resthttp.py
RestHttp.url
def url(proto, server, port=None, uri=None): """Construct a URL from the given components.""" url_parts = [proto, '://', server] if port: port = int(port) if port < 1 or port > 65535: raise ValueError('invalid port value') if not ((proto == 'http' and port == 80) or (proto == 'https' and port == 443)): url_parts.append(':') url_parts.append(str(port)) if uri: url_parts.append('/') url_parts.append(requests.utils.quote(uri.strip('/'))) url_parts.append('/') return ''.join(url_parts)
python
def url(proto, server, port=None, uri=None): """Construct a URL from the given components.""" url_parts = [proto, '://', server] if port: port = int(port) if port < 1 or port > 65535: raise ValueError('invalid port value') if not ((proto == 'http' and port == 80) or (proto == 'https' and port == 443)): url_parts.append(':') url_parts.append(str(port)) if uri: url_parts.append('/') url_parts.append(requests.utils.quote(uri.strip('/'))) url_parts.append('/') return ''.join(url_parts)
[ "def", "url", "(", "proto", ",", "server", ",", "port", "=", "None", ",", "uri", "=", "None", ")", ":", "url_parts", "=", "[", "proto", ",", "'://'", ",", "server", "]", "if", "port", ":", "port", "=", "int", "(", "port", ")", "if", "port", "<", "1", "or", "port", ">", "65535", ":", "raise", "ValueError", "(", "'invalid port value'", ")", "if", "not", "(", "(", "proto", "==", "'http'", "and", "port", "==", "80", ")", "or", "(", "proto", "==", "'https'", "and", "port", "==", "443", ")", ")", ":", "url_parts", ".", "append", "(", "':'", ")", "url_parts", ".", "append", "(", "str", "(", "port", ")", ")", "if", "uri", ":", "url_parts", ".", "append", "(", "'/'", ")", "url_parts", ".", "append", "(", "requests", ".", "utils", ".", "quote", "(", "uri", ".", "strip", "(", "'/'", ")", ")", ")", "url_parts", ".", "append", "(", "'/'", ")", "return", "''", ".", "join", "(", "url_parts", ")" ]
Construct a URL from the given components.
[ "Construct", "a", "URL", "from", "the", "given", "components", "." ]
80ee82bddf2fb2808f3da8ff2c80b7d588e165e8
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/resthttp.py#L112-L129
train
Spirent/py-stcrestclient
stcrestclient/resthttp.py
RestHttp.make_url
def make_url(self, container=None, resource=None, query_items=None): """Create a URL from the specified parts.""" pth = [self._base_url] if container: pth.append(container.strip('/')) if resource: pth.append(resource) else: pth.append('') url = '/'.join(pth) if isinstance(query_items, (list, tuple, set)): url += RestHttp._list_query_str(query_items) query_items = None p = requests.PreparedRequest() p.prepare_url(url, query_items) return p.url
python
def make_url(self, container=None, resource=None, query_items=None): """Create a URL from the specified parts.""" pth = [self._base_url] if container: pth.append(container.strip('/')) if resource: pth.append(resource) else: pth.append('') url = '/'.join(pth) if isinstance(query_items, (list, tuple, set)): url += RestHttp._list_query_str(query_items) query_items = None p = requests.PreparedRequest() p.prepare_url(url, query_items) return p.url
[ "def", "make_url", "(", "self", ",", "container", "=", "None", ",", "resource", "=", "None", ",", "query_items", "=", "None", ")", ":", "pth", "=", "[", "self", ".", "_base_url", "]", "if", "container", ":", "pth", ".", "append", "(", "container", ".", "strip", "(", "'/'", ")", ")", "if", "resource", ":", "pth", ".", "append", "(", "resource", ")", "else", ":", "pth", ".", "append", "(", "''", ")", "url", "=", "'/'", ".", "join", "(", "pth", ")", "if", "isinstance", "(", "query_items", ",", "(", "list", ",", "tuple", ",", "set", ")", ")", ":", "url", "+=", "RestHttp", ".", "_list_query_str", "(", "query_items", ")", "query_items", "=", "None", "p", "=", "requests", ".", "PreparedRequest", "(", ")", "p", ".", "prepare_url", "(", "url", ",", "query_items", ")", "return", "p", ".", "url" ]
Create a URL from the specified parts.
[ "Create", "a", "URL", "from", "the", "specified", "parts", "." ]
80ee82bddf2fb2808f3da8ff2c80b7d588e165e8
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/resthttp.py#L166-L181
train
Spirent/py-stcrestclient
stcrestclient/resthttp.py
RestHttp.head_request
def head_request(self, container, resource=None): """Send a HEAD request.""" url = self.make_url(container, resource) headers = self._make_headers(None) try: rsp = requests.head(url, headers=self._base_headers, verify=self._verify, timeout=self._timeout) except requests.exceptions.ConnectionError as e: RestHttp._raise_conn_error(e) if self._dbg_print: self.__print_req('HEAD', rsp.url, headers, None) return rsp.status_code
python
def head_request(self, container, resource=None): """Send a HEAD request.""" url = self.make_url(container, resource) headers = self._make_headers(None) try: rsp = requests.head(url, headers=self._base_headers, verify=self._verify, timeout=self._timeout) except requests.exceptions.ConnectionError as e: RestHttp._raise_conn_error(e) if self._dbg_print: self.__print_req('HEAD', rsp.url, headers, None) return rsp.status_code
[ "def", "head_request", "(", "self", ",", "container", ",", "resource", "=", "None", ")", ":", "url", "=", "self", ".", "make_url", "(", "container", ",", "resource", ")", "headers", "=", "self", ".", "_make_headers", "(", "None", ")", "try", ":", "rsp", "=", "requests", ".", "head", "(", "url", ",", "headers", "=", "self", ".", "_base_headers", ",", "verify", "=", "self", ".", "_verify", ",", "timeout", "=", "self", ".", "_timeout", ")", "except", "requests", ".", "exceptions", ".", "ConnectionError", "as", "e", ":", "RestHttp", ".", "_raise_conn_error", "(", "e", ")", "if", "self", ".", "_dbg_print", ":", "self", ".", "__print_req", "(", "'HEAD'", ",", "rsp", ".", "url", ",", "headers", ",", "None", ")", "return", "rsp", ".", "status_code" ]
Send a HEAD request.
[ "Send", "a", "HEAD", "request", "." ]
80ee82bddf2fb2808f3da8ff2c80b7d588e165e8
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/resthttp.py#L183-L197
train
Spirent/py-stcrestclient
stcrestclient/resthttp.py
RestHttp.post_request
def post_request(self, container, resource=None, params=None, accept=None): """Send a POST request.""" url = self.make_url(container, resource) headers = self._make_headers(accept) try: rsp = requests.post(url, data=params, headers=headers, verify=self._verify, timeout=self._timeout) except requests.exceptions.ConnectionError as e: RestHttp._raise_conn_error(e) if self._dbg_print: self.__print_req('POST', rsp.url, headers, params) return self._handle_response(rsp)
python
def post_request(self, container, resource=None, params=None, accept=None): """Send a POST request.""" url = self.make_url(container, resource) headers = self._make_headers(accept) try: rsp = requests.post(url, data=params, headers=headers, verify=self._verify, timeout=self._timeout) except requests.exceptions.ConnectionError as e: RestHttp._raise_conn_error(e) if self._dbg_print: self.__print_req('POST', rsp.url, headers, params) return self._handle_response(rsp)
[ "def", "post_request", "(", "self", ",", "container", ",", "resource", "=", "None", ",", "params", "=", "None", ",", "accept", "=", "None", ")", ":", "url", "=", "self", ".", "make_url", "(", "container", ",", "resource", ")", "headers", "=", "self", ".", "_make_headers", "(", "accept", ")", "try", ":", "rsp", "=", "requests", ".", "post", "(", "url", ",", "data", "=", "params", ",", "headers", "=", "headers", ",", "verify", "=", "self", ".", "_verify", ",", "timeout", "=", "self", ".", "_timeout", ")", "except", "requests", ".", "exceptions", ".", "ConnectionError", "as", "e", ":", "RestHttp", ".", "_raise_conn_error", "(", "e", ")", "if", "self", ".", "_dbg_print", ":", "self", ".", "__print_req", "(", "'POST'", ",", "rsp", ".", "url", ",", "headers", ",", "params", ")", "return", "self", ".", "_handle_response", "(", "rsp", ")" ]
Send a POST request.
[ "Send", "a", "POST", "request", "." ]
80ee82bddf2fb2808f3da8ff2c80b7d588e165e8
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/resthttp.py#L220-L234
train
Spirent/py-stcrestclient
stcrestclient/resthttp.py
RestHttp.delete_request
def delete_request(self, container, resource=None, query_items=None, accept=None): """Send a DELETE request.""" url = self.make_url(container, resource) headers = self._make_headers(accept) if query_items and isinstance(query_items, (list, tuple, set)): url += RestHttp._list_query_str(query_items) query_items = None try: rsp = requests.delete(url, params=query_items, headers=headers, verify=self._verify, timeout=self._timeout) except requests.exceptions.ConnectionError as e: RestHttp._raise_conn_error(e) if self._dbg_print: self.__print_req('DELETE', rsp.url, headers, None) return self._handle_response(rsp)
python
def delete_request(self, container, resource=None, query_items=None, accept=None): """Send a DELETE request.""" url = self.make_url(container, resource) headers = self._make_headers(accept) if query_items and isinstance(query_items, (list, tuple, set)): url += RestHttp._list_query_str(query_items) query_items = None try: rsp = requests.delete(url, params=query_items, headers=headers, verify=self._verify, timeout=self._timeout) except requests.exceptions.ConnectionError as e: RestHttp._raise_conn_error(e) if self._dbg_print: self.__print_req('DELETE', rsp.url, headers, None) return self._handle_response(rsp)
[ "def", "delete_request", "(", "self", ",", "container", ",", "resource", "=", "None", ",", "query_items", "=", "None", ",", "accept", "=", "None", ")", ":", "url", "=", "self", ".", "make_url", "(", "container", ",", "resource", ")", "headers", "=", "self", ".", "_make_headers", "(", "accept", ")", "if", "query_items", "and", "isinstance", "(", "query_items", ",", "(", "list", ",", "tuple", ",", "set", ")", ")", ":", "url", "+=", "RestHttp", ".", "_list_query_str", "(", "query_items", ")", "query_items", "=", "None", "try", ":", "rsp", "=", "requests", ".", "delete", "(", "url", ",", "params", "=", "query_items", ",", "headers", "=", "headers", ",", "verify", "=", "self", ".", "_verify", ",", "timeout", "=", "self", ".", "_timeout", ")", "except", "requests", ".", "exceptions", ".", "ConnectionError", "as", "e", ":", "RestHttp", ".", "_raise_conn_error", "(", "e", ")", "if", "self", ".", "_dbg_print", ":", "self", ".", "__print_req", "(", "'DELETE'", ",", "rsp", ".", "url", ",", "headers", ",", "None", ")", "return", "self", ".", "_handle_response", "(", "rsp", ")" ]
Send a DELETE request.
[ "Send", "a", "DELETE", "request", "." ]
80ee82bddf2fb2808f3da8ff2c80b7d588e165e8
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/resthttp.py#L252-L271
train
Spirent/py-stcrestclient
stcrestclient/resthttp.py
RestHttp.download_file
def download_file(self, container, resource, save_path=None, accept=None, query_items=None): """Download a file. If a timeout defined, it is not a time limit on the entire download; rather, an exception is raised if the server has not issued a response for timeout seconds (more precisely, if no bytes have been received on the underlying socket for timeout seconds). If no timeout is specified explicitly, requests do not time out. """ url = self.make_url(container, resource) if not save_path: save_path = resource.split('/')[-1] headers = self._make_headers(accept) if query_items and isinstance(query_items, (list, tuple, set)): url += RestHttp._list_query_str(query_items) query_items = None try: rsp = requests.get(url, query_items, headers=headers, stream=True, verify=self._verify, timeout=self._timeout) except requests.exceptions.ConnectionError as e: RestHttp._raise_conn_error(e) if self._dbg_print: self.__print_req('GET', rsp.url, headers, None) if rsp.status_code >= 300: raise RestHttpError(rsp.status_code, rsp.reason, rsp.text) file_size_dl = 0 try: with open(save_path, 'wb') as f: for buff in rsp.iter_content(chunk_size=16384): f.write(buff) except Exception as e: raise RuntimeError('could not download file: ' + str(e)) finally: rsp.close() if self._dbg_print: print('===> downloaded %d bytes to %s' % (file_size_dl, save_path)) return rsp.status_code, save_path, os.path.getsize(save_path)
python
def download_file(self, container, resource, save_path=None, accept=None, query_items=None): """Download a file. If a timeout defined, it is not a time limit on the entire download; rather, an exception is raised if the server has not issued a response for timeout seconds (more precisely, if no bytes have been received on the underlying socket for timeout seconds). If no timeout is specified explicitly, requests do not time out. """ url = self.make_url(container, resource) if not save_path: save_path = resource.split('/')[-1] headers = self._make_headers(accept) if query_items and isinstance(query_items, (list, tuple, set)): url += RestHttp._list_query_str(query_items) query_items = None try: rsp = requests.get(url, query_items, headers=headers, stream=True, verify=self._verify, timeout=self._timeout) except requests.exceptions.ConnectionError as e: RestHttp._raise_conn_error(e) if self._dbg_print: self.__print_req('GET', rsp.url, headers, None) if rsp.status_code >= 300: raise RestHttpError(rsp.status_code, rsp.reason, rsp.text) file_size_dl = 0 try: with open(save_path, 'wb') as f: for buff in rsp.iter_content(chunk_size=16384): f.write(buff) except Exception as e: raise RuntimeError('could not download file: ' + str(e)) finally: rsp.close() if self._dbg_print: print('===> downloaded %d bytes to %s' % (file_size_dl, save_path)) return rsp.status_code, save_path, os.path.getsize(save_path)
[ "def", "download_file", "(", "self", ",", "container", ",", "resource", ",", "save_path", "=", "None", ",", "accept", "=", "None", ",", "query_items", "=", "None", ")", ":", "url", "=", "self", ".", "make_url", "(", "container", ",", "resource", ")", "if", "not", "save_path", ":", "save_path", "=", "resource", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "headers", "=", "self", ".", "_make_headers", "(", "accept", ")", "if", "query_items", "and", "isinstance", "(", "query_items", ",", "(", "list", ",", "tuple", ",", "set", ")", ")", ":", "url", "+=", "RestHttp", ".", "_list_query_str", "(", "query_items", ")", "query_items", "=", "None", "try", ":", "rsp", "=", "requests", ".", "get", "(", "url", ",", "query_items", ",", "headers", "=", "headers", ",", "stream", "=", "True", ",", "verify", "=", "self", ".", "_verify", ",", "timeout", "=", "self", ".", "_timeout", ")", "except", "requests", ".", "exceptions", ".", "ConnectionError", "as", "e", ":", "RestHttp", ".", "_raise_conn_error", "(", "e", ")", "if", "self", ".", "_dbg_print", ":", "self", ".", "__print_req", "(", "'GET'", ",", "rsp", ".", "url", ",", "headers", ",", "None", ")", "if", "rsp", ".", "status_code", ">=", "300", ":", "raise", "RestHttpError", "(", "rsp", ".", "status_code", ",", "rsp", ".", "reason", ",", "rsp", ".", "text", ")", "file_size_dl", "=", "0", "try", ":", "with", "open", "(", "save_path", ",", "'wb'", ")", "as", "f", ":", "for", "buff", "in", "rsp", ".", "iter_content", "(", "chunk_size", "=", "16384", ")", ":", "f", ".", "write", "(", "buff", ")", "except", "Exception", "as", "e", ":", "raise", "RuntimeError", "(", "'could not download file: '", "+", "str", "(", "e", ")", ")", "finally", ":", "rsp", ".", "close", "(", ")", "if", "self", ".", "_dbg_print", ":", "print", "(", "'===> downloaded %d bytes to %s'", "%", "(", "file_size_dl", ",", "save_path", ")", ")", "return", "rsp", ".", "status_code", ",", "save_path", ",", "os", ".", "path", ".", "getsize", "(", "save_path", ")" ]
Download a file. If a timeout defined, it is not a time limit on the entire download; rather, an exception is raised if the server has not issued a response for timeout seconds (more precisely, if no bytes have been received on the underlying socket for timeout seconds). If no timeout is specified explicitly, requests do not time out.
[ "Download", "a", "file", "." ]
80ee82bddf2fb2808f3da8ff2c80b7d588e165e8
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/resthttp.py#L273-L319
train
Spirent/py-stcrestclient
stcrestclient/resthttp.py
RestHttp.upload_file
def upload_file(self, container, src_file_path, dst_name=None, put=True, content_type=None): """Upload a single file.""" if not os.path.exists(src_file_path): raise RuntimeError('file not found: ' + src_file_path) if not dst_name: dst_name = os.path.basename(src_file_path) if not content_type: content_type = "application/octet.stream" headers = dict(self._base_headers) if content_type: headers["content-length"] = content_type else: headers["content-length"] = "application/octet.stream" headers["content-length"] = str(os.path.getsize(src_file_path)) headers['content-disposition'] = 'attachment; filename=' + dst_name if put: method = 'PUT' url = self.make_url(container, dst_name, None) else: method = 'POST' url = self.make_url(container, None, None) with open(src_file_path, 'rb') as up_file: try: rsp = requests.request(method, url, headers=headers, data=up_file, timeout=self._timeout) except requests.exceptions.ConnectionError as e: RestHttp._raise_conn_error(e) return self._handle_response(rsp)
python
def upload_file(self, container, src_file_path, dst_name=None, put=True, content_type=None): """Upload a single file.""" if not os.path.exists(src_file_path): raise RuntimeError('file not found: ' + src_file_path) if not dst_name: dst_name = os.path.basename(src_file_path) if not content_type: content_type = "application/octet.stream" headers = dict(self._base_headers) if content_type: headers["content-length"] = content_type else: headers["content-length"] = "application/octet.stream" headers["content-length"] = str(os.path.getsize(src_file_path)) headers['content-disposition'] = 'attachment; filename=' + dst_name if put: method = 'PUT' url = self.make_url(container, dst_name, None) else: method = 'POST' url = self.make_url(container, None, None) with open(src_file_path, 'rb') as up_file: try: rsp = requests.request(method, url, headers=headers, data=up_file, timeout=self._timeout) except requests.exceptions.ConnectionError as e: RestHttp._raise_conn_error(e) return self._handle_response(rsp)
[ "def", "upload_file", "(", "self", ",", "container", ",", "src_file_path", ",", "dst_name", "=", "None", ",", "put", "=", "True", ",", "content_type", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "src_file_path", ")", ":", "raise", "RuntimeError", "(", "'file not found: '", "+", "src_file_path", ")", "if", "not", "dst_name", ":", "dst_name", "=", "os", ".", "path", ".", "basename", "(", "src_file_path", ")", "if", "not", "content_type", ":", "content_type", "=", "\"application/octet.stream\"", "headers", "=", "dict", "(", "self", ".", "_base_headers", ")", "if", "content_type", ":", "headers", "[", "\"content-length\"", "]", "=", "content_type", "else", ":", "headers", "[", "\"content-length\"", "]", "=", "\"application/octet.stream\"", "headers", "[", "\"content-length\"", "]", "=", "str", "(", "os", ".", "path", ".", "getsize", "(", "src_file_path", ")", ")", "headers", "[", "'content-disposition'", "]", "=", "'attachment; filename='", "+", "dst_name", "if", "put", ":", "method", "=", "'PUT'", "url", "=", "self", ".", "make_url", "(", "container", ",", "dst_name", ",", "None", ")", "else", ":", "method", "=", "'POST'", "url", "=", "self", ".", "make_url", "(", "container", ",", "None", ",", "None", ")", "with", "open", "(", "src_file_path", ",", "'rb'", ")", "as", "up_file", ":", "try", ":", "rsp", "=", "requests", ".", "request", "(", "method", ",", "url", ",", "headers", "=", "headers", ",", "data", "=", "up_file", ",", "timeout", "=", "self", ".", "_timeout", ")", "except", "requests", ".", "exceptions", ".", "ConnectionError", "as", "e", ":", "RestHttp", ".", "_raise_conn_error", "(", "e", ")", "return", "self", ".", "_handle_response", "(", "rsp", ")" ]
Upload a single file.
[ "Upload", "a", "single", "file", "." ]
80ee82bddf2fb2808f3da8ff2c80b7d588e165e8
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/resthttp.py#L321-L350
train
Spirent/py-stcrestclient
stcrestclient/resthttp.py
RestHttp.upload_file_mp
def upload_file_mp(self, container, src_file_path, dst_name=None, content_type=None): """Upload a file using multi-part encoding.""" if not os.path.exists(src_file_path): raise RuntimeError('file not found: ' + src_file_path) if not dst_name: dst_name = os.path.basename(src_file_path) if not content_type: content_type = "application/octet.stream" url = self.make_url(container, None, None) headers = self._base_headers with open(src_file_path, 'rb') as up_file: files = {'file': (dst_name, up_file, content_type)} try: rsp = requests.post(url, headers=headers, files=files, timeout=self._timeout) except requests.exceptions.ConnectionError as e: RestHttp._raise_conn_error(e) return self._handle_response(rsp)
python
def upload_file_mp(self, container, src_file_path, dst_name=None, content_type=None): """Upload a file using multi-part encoding.""" if not os.path.exists(src_file_path): raise RuntimeError('file not found: ' + src_file_path) if not dst_name: dst_name = os.path.basename(src_file_path) if not content_type: content_type = "application/octet.stream" url = self.make_url(container, None, None) headers = self._base_headers with open(src_file_path, 'rb') as up_file: files = {'file': (dst_name, up_file, content_type)} try: rsp = requests.post(url, headers=headers, files=files, timeout=self._timeout) except requests.exceptions.ConnectionError as e: RestHttp._raise_conn_error(e) return self._handle_response(rsp)
[ "def", "upload_file_mp", "(", "self", ",", "container", ",", "src_file_path", ",", "dst_name", "=", "None", ",", "content_type", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "src_file_path", ")", ":", "raise", "RuntimeError", "(", "'file not found: '", "+", "src_file_path", ")", "if", "not", "dst_name", ":", "dst_name", "=", "os", ".", "path", ".", "basename", "(", "src_file_path", ")", "if", "not", "content_type", ":", "content_type", "=", "\"application/octet.stream\"", "url", "=", "self", ".", "make_url", "(", "container", ",", "None", ",", "None", ")", "headers", "=", "self", ".", "_base_headers", "with", "open", "(", "src_file_path", ",", "'rb'", ")", "as", "up_file", ":", "files", "=", "{", "'file'", ":", "(", "dst_name", ",", "up_file", ",", "content_type", ")", "}", "try", ":", "rsp", "=", "requests", ".", "post", "(", "url", ",", "headers", "=", "headers", ",", "files", "=", "files", ",", "timeout", "=", "self", ".", "_timeout", ")", "except", "requests", ".", "exceptions", ".", "ConnectionError", "as", "e", ":", "RestHttp", ".", "_raise_conn_error", "(", "e", ")", "return", "self", ".", "_handle_response", "(", "rsp", ")" ]
Upload a file using multi-part encoding.
[ "Upload", "a", "file", "using", "multi", "-", "part", "encoding", "." ]
80ee82bddf2fb2808f3da8ff2c80b7d588e165e8
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/resthttp.py#L352-L371
train
Spirent/py-stcrestclient
stcrestclient/resthttp.py
RestHttp.upload_files
def upload_files(self, container, src_dst_map, content_type=None): """Upload multiple files.""" if not content_type: content_type = "application/octet.stream" url = self.make_url(container, None, None) headers = self._base_headers multi_files = [] try: for src_path in src_dst_map: dst_name = src_dst_map[src_path] if not dst_name: dst_name = os.path.basename(src_path) multi_files.append( ('files', (dst_name, open(src_path, 'rb'), content_type))) rsp = requests.post(url, headers=headers, files=multi_files, timeout=self._timeout) except requests.exceptions.ConnectionError as e: RestHttp._raise_conn_error(e) finally: for n, info in multi_files: dst, f, ctype = info f.close() return self._handle_response(rsp)
python
def upload_files(self, container, src_dst_map, content_type=None): """Upload multiple files.""" if not content_type: content_type = "application/octet.stream" url = self.make_url(container, None, None) headers = self._base_headers multi_files = [] try: for src_path in src_dst_map: dst_name = src_dst_map[src_path] if not dst_name: dst_name = os.path.basename(src_path) multi_files.append( ('files', (dst_name, open(src_path, 'rb'), content_type))) rsp = requests.post(url, headers=headers, files=multi_files, timeout=self._timeout) except requests.exceptions.ConnectionError as e: RestHttp._raise_conn_error(e) finally: for n, info in multi_files: dst, f, ctype = info f.close() return self._handle_response(rsp)
[ "def", "upload_files", "(", "self", ",", "container", ",", "src_dst_map", ",", "content_type", "=", "None", ")", ":", "if", "not", "content_type", ":", "content_type", "=", "\"application/octet.stream\"", "url", "=", "self", ".", "make_url", "(", "container", ",", "None", ",", "None", ")", "headers", "=", "self", ".", "_base_headers", "multi_files", "=", "[", "]", "try", ":", "for", "src_path", "in", "src_dst_map", ":", "dst_name", "=", "src_dst_map", "[", "src_path", "]", "if", "not", "dst_name", ":", "dst_name", "=", "os", ".", "path", ".", "basename", "(", "src_path", ")", "multi_files", ".", "append", "(", "(", "'files'", ",", "(", "dst_name", ",", "open", "(", "src_path", ",", "'rb'", ")", ",", "content_type", ")", ")", ")", "rsp", "=", "requests", ".", "post", "(", "url", ",", "headers", "=", "headers", ",", "files", "=", "multi_files", ",", "timeout", "=", "self", ".", "_timeout", ")", "except", "requests", ".", "exceptions", ".", "ConnectionError", "as", "e", ":", "RestHttp", ".", "_raise_conn_error", "(", "e", ")", "finally", ":", "for", "n", ",", "info", "in", "multi_files", ":", "dst", ",", "f", ",", "ctype", "=", "info", "f", ".", "close", "(", ")", "return", "self", ".", "_handle_response", "(", "rsp", ")" ]
Upload multiple files.
[ "Upload", "multiple", "files", "." ]
80ee82bddf2fb2808f3da8ff2c80b7d588e165e8
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/resthttp.py#L373-L397
train
Spirent/py-stcrestclient
stcrestclient/stcpythonrest.py
StcPythonRest.new_session
def new_session(self, server=None, session_name=None, user_name=None, existing_session=None): """Create a new session or attach to existing. Normally, this function is called automatically, and gets its parameter values from the environment. It is provided as a public function for cases when extra control over session creation is required in an automation script that is adapted to use ReST. WARNING: This function is not part of the original StcPython.py and if called directly by an automation script, then that script will not be able to revert to using the non-ReST API until the call to this function is removed. Arguments: server -- STC server (Lab Server) address. If not set get value from STC_SERVER_ADDRESS environment variable. session_name -- Name part of session ID. If not set get value from STC_SESSION_NAME environment variable. user_name -- User portion of session ID. If not set get name of user this script is running as. existing_session -- Behavior when session already exists. Recognized values are 'kill' and 'join'. If not set get value from EXISTING_SESSION environment variable. If not set to recognized value, raise exception if session already exists. See also: stchttp.StcHttp(), stchttp.new_session() Return: The internal StcHttp object that is used for this session. This allows the caller to perform additional interactions with the STC ReST API beyond what the adapter provides. """ if not server: server = os.environ.get('STC_SERVER_ADDRESS') if not server: raise EnvironmentError('STC_SERVER_ADDRESS not set') self._stc = stchttp.StcHttp(server) if not session_name: session_name = os.environ.get('STC_SESSION_NAME') if not session_name or session_name == '__NEW_TEST_SESSION__': session_name = None if not user_name: try: # Try to get the name of the current user. user_name = getpass.getuser() except: pass if not existing_session: # Try to get existing_session from environ if not passed in. existing_session = os.environ.get('EXISTING_SESSION') if existing_session: existing_session = existing_session.lower() if existing_session == 'kill': # Kill any existing session and create a new one. self._stc.new_session(user_name, session_name, True) return self._stc if existing_session == 'join': # Create a new session, or join if already exists. try: self._stc.new_session(user_name, session_name, False) except RuntimeError as e: if str(e).find('already exists') >= 0: sid = ' - '.join((session_name, user_name)) self._stc.join_session(sid) else: raise return self._stc # Create a new session, raise exception if session already exists. self._stc.new_session(user_name, session_name, False) return self._stc
python
def new_session(self, server=None, session_name=None, user_name=None, existing_session=None): """Create a new session or attach to existing. Normally, this function is called automatically, and gets its parameter values from the environment. It is provided as a public function for cases when extra control over session creation is required in an automation script that is adapted to use ReST. WARNING: This function is not part of the original StcPython.py and if called directly by an automation script, then that script will not be able to revert to using the non-ReST API until the call to this function is removed. Arguments: server -- STC server (Lab Server) address. If not set get value from STC_SERVER_ADDRESS environment variable. session_name -- Name part of session ID. If not set get value from STC_SESSION_NAME environment variable. user_name -- User portion of session ID. If not set get name of user this script is running as. existing_session -- Behavior when session already exists. Recognized values are 'kill' and 'join'. If not set get value from EXISTING_SESSION environment variable. If not set to recognized value, raise exception if session already exists. See also: stchttp.StcHttp(), stchttp.new_session() Return: The internal StcHttp object that is used for this session. This allows the caller to perform additional interactions with the STC ReST API beyond what the adapter provides. """ if not server: server = os.environ.get('STC_SERVER_ADDRESS') if not server: raise EnvironmentError('STC_SERVER_ADDRESS not set') self._stc = stchttp.StcHttp(server) if not session_name: session_name = os.environ.get('STC_SESSION_NAME') if not session_name or session_name == '__NEW_TEST_SESSION__': session_name = None if not user_name: try: # Try to get the name of the current user. user_name = getpass.getuser() except: pass if not existing_session: # Try to get existing_session from environ if not passed in. existing_session = os.environ.get('EXISTING_SESSION') if existing_session: existing_session = existing_session.lower() if existing_session == 'kill': # Kill any existing session and create a new one. self._stc.new_session(user_name, session_name, True) return self._stc if existing_session == 'join': # Create a new session, or join if already exists. try: self._stc.new_session(user_name, session_name, False) except RuntimeError as e: if str(e).find('already exists') >= 0: sid = ' - '.join((session_name, user_name)) self._stc.join_session(sid) else: raise return self._stc # Create a new session, raise exception if session already exists. self._stc.new_session(user_name, session_name, False) return self._stc
[ "def", "new_session", "(", "self", ",", "server", "=", "None", ",", "session_name", "=", "None", ",", "user_name", "=", "None", ",", "existing_session", "=", "None", ")", ":", "if", "not", "server", ":", "server", "=", "os", ".", "environ", ".", "get", "(", "'STC_SERVER_ADDRESS'", ")", "if", "not", "server", ":", "raise", "EnvironmentError", "(", "'STC_SERVER_ADDRESS not set'", ")", "self", ".", "_stc", "=", "stchttp", ".", "StcHttp", "(", "server", ")", "if", "not", "session_name", ":", "session_name", "=", "os", ".", "environ", ".", "get", "(", "'STC_SESSION_NAME'", ")", "if", "not", "session_name", "or", "session_name", "==", "'__NEW_TEST_SESSION__'", ":", "session_name", "=", "None", "if", "not", "user_name", ":", "try", ":", "# Try to get the name of the current user.", "user_name", "=", "getpass", ".", "getuser", "(", ")", "except", ":", "pass", "if", "not", "existing_session", ":", "# Try to get existing_session from environ if not passed in.", "existing_session", "=", "os", ".", "environ", ".", "get", "(", "'EXISTING_SESSION'", ")", "if", "existing_session", ":", "existing_session", "=", "existing_session", ".", "lower", "(", ")", "if", "existing_session", "==", "'kill'", ":", "# Kill any existing session and create a new one.", "self", ".", "_stc", ".", "new_session", "(", "user_name", ",", "session_name", ",", "True", ")", "return", "self", ".", "_stc", "if", "existing_session", "==", "'join'", ":", "# Create a new session, or join if already exists.", "try", ":", "self", ".", "_stc", ".", "new_session", "(", "user_name", ",", "session_name", ",", "False", ")", "except", "RuntimeError", "as", "e", ":", "if", "str", "(", "e", ")", ".", "find", "(", "'already exists'", ")", ">=", "0", ":", "sid", "=", "' - '", ".", "join", "(", "(", "session_name", ",", "user_name", ")", ")", "self", ".", "_stc", ".", "join_session", "(", "sid", ")", "else", ":", "raise", "return", "self", ".", "_stc", "# Create a new session, raise exception if session already exists.", "self", ".", "_stc", ".", "new_session", "(", "user_name", ",", "session_name", ",", "False", ")", "return", "self", ".", "_stc" ]
Create a new session or attach to existing. Normally, this function is called automatically, and gets its parameter values from the environment. It is provided as a public function for cases when extra control over session creation is required in an automation script that is adapted to use ReST. WARNING: This function is not part of the original StcPython.py and if called directly by an automation script, then that script will not be able to revert to using the non-ReST API until the call to this function is removed. Arguments: server -- STC server (Lab Server) address. If not set get value from STC_SERVER_ADDRESS environment variable. session_name -- Name part of session ID. If not set get value from STC_SESSION_NAME environment variable. user_name -- User portion of session ID. If not set get name of user this script is running as. existing_session -- Behavior when session already exists. Recognized values are 'kill' and 'join'. If not set get value from EXISTING_SESSION environment variable. If not set to recognized value, raise exception if session already exists. See also: stchttp.StcHttp(), stchttp.new_session() Return: The internal StcHttp object that is used for this session. This allows the caller to perform additional interactions with the STC ReST API beyond what the adapter provides.
[ "Create", "a", "new", "session", "or", "attach", "to", "existing", "." ]
80ee82bddf2fb2808f3da8ff2c80b7d588e165e8
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/stcpythonrest.py#L192-L267
train
Spirent/py-stcrestclient
stcrestclient/stcpythonrest.py
StcPythonRest._end_session
def _end_session(self, kill=None): """End the client session.""" if self._stc: if kill is None: kill = os.environ.get('STC_SESSION_TERMINATE_ON_DISCONNECT') kill = _is_true(kill) self._stc.end_session(kill) self._stc = None
python
def _end_session(self, kill=None): """End the client session.""" if self._stc: if kill is None: kill = os.environ.get('STC_SESSION_TERMINATE_ON_DISCONNECT') kill = _is_true(kill) self._stc.end_session(kill) self._stc = None
[ "def", "_end_session", "(", "self", ",", "kill", "=", "None", ")", ":", "if", "self", ".", "_stc", ":", "if", "kill", "is", "None", ":", "kill", "=", "os", ".", "environ", ".", "get", "(", "'STC_SESSION_TERMINATE_ON_DISCONNECT'", ")", "kill", "=", "_is_true", "(", "kill", ")", "self", ".", "_stc", ".", "end_session", "(", "kill", ")", "self", ".", "_stc", "=", "None" ]
End the client session.
[ "End", "the", "client", "session", "." ]
80ee82bddf2fb2808f3da8ff2c80b7d588e165e8
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/stcpythonrest.py#L274-L281
train
rtfd/readthedocs-sphinx-ext
readthedocs_ext/embed.py
setup
def setup(app): """ This isn't used in Production, but allows this module to be used as a standalone extension. """ app.add_directive('readthedocs-embed', EmbedDirective) app.add_config_value('readthedocs_embed_project', '', 'html') app.add_config_value('readthedocs_embed_version', '', 'html') app.add_config_value('readthedocs_embed_doc', '', 'html') return app
python
def setup(app): """ This isn't used in Production, but allows this module to be used as a standalone extension. """ app.add_directive('readthedocs-embed', EmbedDirective) app.add_config_value('readthedocs_embed_project', '', 'html') app.add_config_value('readthedocs_embed_version', '', 'html') app.add_config_value('readthedocs_embed_doc', '', 'html') return app
[ "def", "setup", "(", "app", ")", ":", "app", ".", "add_directive", "(", "'readthedocs-embed'", ",", "EmbedDirective", ")", "app", ".", "add_config_value", "(", "'readthedocs_embed_project'", ",", "''", ",", "'html'", ")", "app", ".", "add_config_value", "(", "'readthedocs_embed_version'", ",", "''", ",", "'html'", ")", "app", ".", "add_config_value", "(", "'readthedocs_embed_doc'", ",", "''", ",", "'html'", ")", "return", "app" ]
This isn't used in Production, but allows this module to be used as a standalone extension.
[ "This", "isn", "t", "used", "in", "Production", "but", "allows", "this", "module", "to", "be", "used", "as", "a", "standalone", "extension", "." ]
f1a01c51c675d36ac365162ea06814544c2aa410
https://github.com/rtfd/readthedocs-sphinx-ext/blob/f1a01c51c675d36ac365162ea06814544c2aa410/readthedocs_ext/embed.py#L66-L77
train
rtfd/readthedocs-sphinx-ext
readthedocs_ext/readthedocs.py
finalize_media
def finalize_media(app): """Point media files at our media server.""" if (app.builder.name == 'readthedocssinglehtmllocalmedia' or app.builder.format != 'html' or not hasattr(app.builder, 'script_files')): return # Use local media for downloadable files # Pull project data from conf.py if it exists context = app.builder.config.html_context STATIC_URL = context.get('STATIC_URL', DEFAULT_STATIC_URL) js_file = '{}javascript/readthedocs-doc-embed.js'.format(STATIC_URL) if sphinx.version_info < (1, 8): app.builder.script_files.append(js_file) else: app.add_js_file(js_file)
python
def finalize_media(app): """Point media files at our media server.""" if (app.builder.name == 'readthedocssinglehtmllocalmedia' or app.builder.format != 'html' or not hasattr(app.builder, 'script_files')): return # Use local media for downloadable files # Pull project data from conf.py if it exists context = app.builder.config.html_context STATIC_URL = context.get('STATIC_URL', DEFAULT_STATIC_URL) js_file = '{}javascript/readthedocs-doc-embed.js'.format(STATIC_URL) if sphinx.version_info < (1, 8): app.builder.script_files.append(js_file) else: app.add_js_file(js_file)
[ "def", "finalize_media", "(", "app", ")", ":", "if", "(", "app", ".", "builder", ".", "name", "==", "'readthedocssinglehtmllocalmedia'", "or", "app", ".", "builder", ".", "format", "!=", "'html'", "or", "not", "hasattr", "(", "app", ".", "builder", ",", "'script_files'", ")", ")", ":", "return", "# Use local media for downloadable files", "# Pull project data from conf.py if it exists", "context", "=", "app", ".", "builder", ".", "config", ".", "html_context", "STATIC_URL", "=", "context", ".", "get", "(", "'STATIC_URL'", ",", "DEFAULT_STATIC_URL", ")", "js_file", "=", "'{}javascript/readthedocs-doc-embed.js'", ".", "format", "(", "STATIC_URL", ")", "if", "sphinx", ".", "version_info", "<", "(", "1", ",", "8", ")", ":", "app", ".", "builder", ".", "script_files", ".", "append", "(", "js_file", ")", "else", ":", "app", ".", "add_js_file", "(", "js_file", ")" ]
Point media files at our media server.
[ "Point", "media", "files", "at", "our", "media", "server", "." ]
f1a01c51c675d36ac365162ea06814544c2aa410
https://github.com/rtfd/readthedocs-sphinx-ext/blob/f1a01c51c675d36ac365162ea06814544c2aa410/readthedocs_ext/readthedocs.py#L43-L57
train
rtfd/readthedocs-sphinx-ext
readthedocs_ext/readthedocs.py
update_body
def update_body(app, pagename, templatename, context, doctree): """ Add Read the Docs content to Sphinx body content. This is the most reliable way to inject our content into the page. """ STATIC_URL = context.get('STATIC_URL', DEFAULT_STATIC_URL) online_builders = [ 'readthedocs', 'readthedocsdirhtml', 'readthedocssinglehtml' ] if app.builder.name == 'readthedocssinglehtmllocalmedia': if 'html_theme' in context and context['html_theme'] == 'sphinx_rtd_theme': theme_css = '_static/css/theme.css' else: theme_css = '_static/css/badge_only.css' elif app.builder.name in online_builders: if 'html_theme' in context and context['html_theme'] == 'sphinx_rtd_theme': theme_css = '%scss/sphinx_rtd_theme.css' % STATIC_URL else: theme_css = '%scss/badge_only.css' % STATIC_URL else: # Only insert on our HTML builds return inject_css = True # Starting at v0.4.0 of the sphinx theme, the theme CSS should not be injected # This decouples the theme CSS (which is versioned independently) from readthedocs.org if theme_css.endswith('sphinx_rtd_theme.css'): try: import sphinx_rtd_theme inject_css = LooseVersion(sphinx_rtd_theme.__version__) < LooseVersion('0.4.0') except ImportError: pass if inject_css and theme_css not in app.builder.css_files: if sphinx.version_info < (1, 8): app.builder.css_files.insert(0, theme_css) else: app.add_css_file(theme_css) # This is monkey patched on the signal because we can't know what the user # has done with their `app.builder.templates` before now. if not hasattr(app.builder.templates.render, '_patched'): # Janky monkey patch of template rendering to add our content old_render = app.builder.templates.render def rtd_render(self, template, render_context): """ A decorator that renders the content with the users template renderer, then adds the Read the Docs HTML content at the end of body. """ # Render Read the Docs content template_context = render_context.copy() template_context['rtd_css_url'] = '{}css/readthedocs-doc-embed.css'.format(STATIC_URL) template_context['rtd_analytics_url'] = '{}javascript/readthedocs-analytics.js'.format( STATIC_URL, ) source = os.path.join( os.path.abspath(os.path.dirname(__file__)), '_templates', 'readthedocs-insert.html.tmpl' ) templ = open(source).read() rtd_content = app.builder.templates.render_string(templ, template_context) # Handle original render function content = old_render(template, render_context) end_body = content.lower().find('</head>') # Insert our content at the end of the body. if end_body != -1: content = content[:end_body] + rtd_content + "\n" + content[end_body:] else: log.debug("File doesn't look like HTML. Skipping RTD content addition") return content rtd_render._patched = True app.builder.templates.render = types.MethodType(rtd_render, app.builder.templates)
python
def update_body(app, pagename, templatename, context, doctree): """ Add Read the Docs content to Sphinx body content. This is the most reliable way to inject our content into the page. """ STATIC_URL = context.get('STATIC_URL', DEFAULT_STATIC_URL) online_builders = [ 'readthedocs', 'readthedocsdirhtml', 'readthedocssinglehtml' ] if app.builder.name == 'readthedocssinglehtmllocalmedia': if 'html_theme' in context and context['html_theme'] == 'sphinx_rtd_theme': theme_css = '_static/css/theme.css' else: theme_css = '_static/css/badge_only.css' elif app.builder.name in online_builders: if 'html_theme' in context and context['html_theme'] == 'sphinx_rtd_theme': theme_css = '%scss/sphinx_rtd_theme.css' % STATIC_URL else: theme_css = '%scss/badge_only.css' % STATIC_URL else: # Only insert on our HTML builds return inject_css = True # Starting at v0.4.0 of the sphinx theme, the theme CSS should not be injected # This decouples the theme CSS (which is versioned independently) from readthedocs.org if theme_css.endswith('sphinx_rtd_theme.css'): try: import sphinx_rtd_theme inject_css = LooseVersion(sphinx_rtd_theme.__version__) < LooseVersion('0.4.0') except ImportError: pass if inject_css and theme_css not in app.builder.css_files: if sphinx.version_info < (1, 8): app.builder.css_files.insert(0, theme_css) else: app.add_css_file(theme_css) # This is monkey patched on the signal because we can't know what the user # has done with their `app.builder.templates` before now. if not hasattr(app.builder.templates.render, '_patched'): # Janky monkey patch of template rendering to add our content old_render = app.builder.templates.render def rtd_render(self, template, render_context): """ A decorator that renders the content with the users template renderer, then adds the Read the Docs HTML content at the end of body. """ # Render Read the Docs content template_context = render_context.copy() template_context['rtd_css_url'] = '{}css/readthedocs-doc-embed.css'.format(STATIC_URL) template_context['rtd_analytics_url'] = '{}javascript/readthedocs-analytics.js'.format( STATIC_URL, ) source = os.path.join( os.path.abspath(os.path.dirname(__file__)), '_templates', 'readthedocs-insert.html.tmpl' ) templ = open(source).read() rtd_content = app.builder.templates.render_string(templ, template_context) # Handle original render function content = old_render(template, render_context) end_body = content.lower().find('</head>') # Insert our content at the end of the body. if end_body != -1: content = content[:end_body] + rtd_content + "\n" + content[end_body:] else: log.debug("File doesn't look like HTML. Skipping RTD content addition") return content rtd_render._patched = True app.builder.templates.render = types.MethodType(rtd_render, app.builder.templates)
[ "def", "update_body", "(", "app", ",", "pagename", ",", "templatename", ",", "context", ",", "doctree", ")", ":", "STATIC_URL", "=", "context", ".", "get", "(", "'STATIC_URL'", ",", "DEFAULT_STATIC_URL", ")", "online_builders", "=", "[", "'readthedocs'", ",", "'readthedocsdirhtml'", ",", "'readthedocssinglehtml'", "]", "if", "app", ".", "builder", ".", "name", "==", "'readthedocssinglehtmllocalmedia'", ":", "if", "'html_theme'", "in", "context", "and", "context", "[", "'html_theme'", "]", "==", "'sphinx_rtd_theme'", ":", "theme_css", "=", "'_static/css/theme.css'", "else", ":", "theme_css", "=", "'_static/css/badge_only.css'", "elif", "app", ".", "builder", ".", "name", "in", "online_builders", ":", "if", "'html_theme'", "in", "context", "and", "context", "[", "'html_theme'", "]", "==", "'sphinx_rtd_theme'", ":", "theme_css", "=", "'%scss/sphinx_rtd_theme.css'", "%", "STATIC_URL", "else", ":", "theme_css", "=", "'%scss/badge_only.css'", "%", "STATIC_URL", "else", ":", "# Only insert on our HTML builds", "return", "inject_css", "=", "True", "# Starting at v0.4.0 of the sphinx theme, the theme CSS should not be injected", "# This decouples the theme CSS (which is versioned independently) from readthedocs.org", "if", "theme_css", ".", "endswith", "(", "'sphinx_rtd_theme.css'", ")", ":", "try", ":", "import", "sphinx_rtd_theme", "inject_css", "=", "LooseVersion", "(", "sphinx_rtd_theme", ".", "__version__", ")", "<", "LooseVersion", "(", "'0.4.0'", ")", "except", "ImportError", ":", "pass", "if", "inject_css", "and", "theme_css", "not", "in", "app", ".", "builder", ".", "css_files", ":", "if", "sphinx", ".", "version_info", "<", "(", "1", ",", "8", ")", ":", "app", ".", "builder", ".", "css_files", ".", "insert", "(", "0", ",", "theme_css", ")", "else", ":", "app", ".", "add_css_file", "(", "theme_css", ")", "# This is monkey patched on the signal because we can't know what the user", "# has done with their `app.builder.templates` before now.", "if", "not", "hasattr", "(", "app", ".", "builder", ".", "templates", ".", "render", ",", "'_patched'", ")", ":", "# Janky monkey patch of template rendering to add our content", "old_render", "=", "app", ".", "builder", ".", "templates", ".", "render", "def", "rtd_render", "(", "self", ",", "template", ",", "render_context", ")", ":", "\"\"\"\n A decorator that renders the content with the users template renderer,\n then adds the Read the Docs HTML content at the end of body.\n \"\"\"", "# Render Read the Docs content", "template_context", "=", "render_context", ".", "copy", "(", ")", "template_context", "[", "'rtd_css_url'", "]", "=", "'{}css/readthedocs-doc-embed.css'", ".", "format", "(", "STATIC_URL", ")", "template_context", "[", "'rtd_analytics_url'", "]", "=", "'{}javascript/readthedocs-analytics.js'", ".", "format", "(", "STATIC_URL", ",", ")", "source", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", ",", "'_templates'", ",", "'readthedocs-insert.html.tmpl'", ")", "templ", "=", "open", "(", "source", ")", ".", "read", "(", ")", "rtd_content", "=", "app", ".", "builder", ".", "templates", ".", "render_string", "(", "templ", ",", "template_context", ")", "# Handle original render function", "content", "=", "old_render", "(", "template", ",", "render_context", ")", "end_body", "=", "content", ".", "lower", "(", ")", ".", "find", "(", "'</head>'", ")", "# Insert our content at the end of the body.", "if", "end_body", "!=", "-", "1", ":", "content", "=", "content", "[", ":", "end_body", "]", "+", "rtd_content", "+", "\"\\n\"", "+", "content", "[", "end_body", ":", "]", "else", ":", "log", ".", "debug", "(", "\"File doesn't look like HTML. Skipping RTD content addition\"", ")", "return", "content", "rtd_render", ".", "_patched", "=", "True", "app", ".", "builder", ".", "templates", ".", "render", "=", "types", ".", "MethodType", "(", "rtd_render", ",", "app", ".", "builder", ".", "templates", ")" ]
Add Read the Docs content to Sphinx body content. This is the most reliable way to inject our content into the page.
[ "Add", "Read", "the", "Docs", "content", "to", "Sphinx", "body", "content", "." ]
f1a01c51c675d36ac365162ea06814544c2aa410
https://github.com/rtfd/readthedocs-sphinx-ext/blob/f1a01c51c675d36ac365162ea06814544c2aa410/readthedocs_ext/readthedocs.py#L60-L142
train
rtfd/readthedocs-sphinx-ext
readthedocs_ext/readthedocs.py
generate_json_artifacts
def generate_json_artifacts(app, pagename, templatename, context, doctree): """ Generate JSON artifacts for each page. This way we can skip generating this in other build step. """ try: # We need to get the output directory where the docs are built # _build/json. build_json = os.path.abspath( os.path.join(app.outdir, '..', 'json') ) outjson = os.path.join(build_json, pagename + '.fjson') outdir = os.path.dirname(outjson) if not os.path.exists(outdir): os.makedirs(outdir) with open(outjson, 'w+') as json_file: to_context = { key: context.get(key, '') for key in KEYS } json.dump(to_context, json_file, indent=4) except TypeError: log.exception( 'Fail to encode JSON for page {page}'.format(page=outjson) ) except IOError: log.exception( 'Fail to save JSON output for page {page}'.format(page=outjson) ) except Exception as e: log.exception( 'Failure in JSON search dump for page {page}'.format(page=outjson) )
python
def generate_json_artifacts(app, pagename, templatename, context, doctree): """ Generate JSON artifacts for each page. This way we can skip generating this in other build step. """ try: # We need to get the output directory where the docs are built # _build/json. build_json = os.path.abspath( os.path.join(app.outdir, '..', 'json') ) outjson = os.path.join(build_json, pagename + '.fjson') outdir = os.path.dirname(outjson) if not os.path.exists(outdir): os.makedirs(outdir) with open(outjson, 'w+') as json_file: to_context = { key: context.get(key, '') for key in KEYS } json.dump(to_context, json_file, indent=4) except TypeError: log.exception( 'Fail to encode JSON for page {page}'.format(page=outjson) ) except IOError: log.exception( 'Fail to save JSON output for page {page}'.format(page=outjson) ) except Exception as e: log.exception( 'Failure in JSON search dump for page {page}'.format(page=outjson) )
[ "def", "generate_json_artifacts", "(", "app", ",", "pagename", ",", "templatename", ",", "context", ",", "doctree", ")", ":", "try", ":", "# We need to get the output directory where the docs are built", "# _build/json.", "build_json", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "app", ".", "outdir", ",", "'..'", ",", "'json'", ")", ")", "outjson", "=", "os", ".", "path", ".", "join", "(", "build_json", ",", "pagename", "+", "'.fjson'", ")", "outdir", "=", "os", ".", "path", ".", "dirname", "(", "outjson", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "outdir", ")", ":", "os", ".", "makedirs", "(", "outdir", ")", "with", "open", "(", "outjson", ",", "'w+'", ")", "as", "json_file", ":", "to_context", "=", "{", "key", ":", "context", ".", "get", "(", "key", ",", "''", ")", "for", "key", "in", "KEYS", "}", "json", ".", "dump", "(", "to_context", ",", "json_file", ",", "indent", "=", "4", ")", "except", "TypeError", ":", "log", ".", "exception", "(", "'Fail to encode JSON for page {page}'", ".", "format", "(", "page", "=", "outjson", ")", ")", "except", "IOError", ":", "log", ".", "exception", "(", "'Fail to save JSON output for page {page}'", ".", "format", "(", "page", "=", "outjson", ")", ")", "except", "Exception", "as", "e", ":", "log", ".", "exception", "(", "'Failure in JSON search dump for page {page}'", ".", "format", "(", "page", "=", "outjson", ")", ")" ]
Generate JSON artifacts for each page. This way we can skip generating this in other build step.
[ "Generate", "JSON", "artifacts", "for", "each", "page", "." ]
f1a01c51c675d36ac365162ea06814544c2aa410
https://github.com/rtfd/readthedocs-sphinx-ext/blob/f1a01c51c675d36ac365162ea06814544c2aa410/readthedocs_ext/readthedocs.py#L145-L178
train
rtfd/readthedocs-sphinx-ext
readthedocs_ext/readthedocs.py
HtmlBuilderMixin._copy_searchtools
def _copy_searchtools(self, renderer=None): """Copy and patch searchtools This uses the included Sphinx version's searchtools, but patches it to remove automatic initialization. This is a fork of ``sphinx.util.fileutil.copy_asset`` """ log.info(bold('copying searchtools... '), nonl=True) if sphinx.version_info < (1, 8): search_js_file = 'searchtools.js_t' else: search_js_file = 'searchtools.js' path_src = os.path.join( package_dir, 'themes', 'basic', 'static', search_js_file ) if os.path.exists(path_src): path_dest = os.path.join(self.outdir, '_static', 'searchtools.js') if renderer is None: # Sphinx 1.4 used the renderer from the existing builder, but # the pattern for Sphinx 1.5 is to pass in a renderer separate # from the builder. This supports both patterns for future # compatibility if sphinx.version_info < (1, 5): renderer = self.templates else: from sphinx.util.template import SphinxRenderer renderer = SphinxRenderer() with codecs.open(path_src, 'r', encoding='utf-8') as h_src: with codecs.open(path_dest, 'w', encoding='utf-8') as h_dest: data = h_src.read() data = self.REPLACEMENT_PATTERN.sub(self.REPLACEMENT_TEXT, data) h_dest.write(renderer.render_string( data, self.get_static_readthedocs_context() )) else: log.warning('Missing {}'.format(search_js_file)) log.info('done')
python
def _copy_searchtools(self, renderer=None): """Copy and patch searchtools This uses the included Sphinx version's searchtools, but patches it to remove automatic initialization. This is a fork of ``sphinx.util.fileutil.copy_asset`` """ log.info(bold('copying searchtools... '), nonl=True) if sphinx.version_info < (1, 8): search_js_file = 'searchtools.js_t' else: search_js_file = 'searchtools.js' path_src = os.path.join( package_dir, 'themes', 'basic', 'static', search_js_file ) if os.path.exists(path_src): path_dest = os.path.join(self.outdir, '_static', 'searchtools.js') if renderer is None: # Sphinx 1.4 used the renderer from the existing builder, but # the pattern for Sphinx 1.5 is to pass in a renderer separate # from the builder. This supports both patterns for future # compatibility if sphinx.version_info < (1, 5): renderer = self.templates else: from sphinx.util.template import SphinxRenderer renderer = SphinxRenderer() with codecs.open(path_src, 'r', encoding='utf-8') as h_src: with codecs.open(path_dest, 'w', encoding='utf-8') as h_dest: data = h_src.read() data = self.REPLACEMENT_PATTERN.sub(self.REPLACEMENT_TEXT, data) h_dest.write(renderer.render_string( data, self.get_static_readthedocs_context() )) else: log.warning('Missing {}'.format(search_js_file)) log.info('done')
[ "def", "_copy_searchtools", "(", "self", ",", "renderer", "=", "None", ")", ":", "log", ".", "info", "(", "bold", "(", "'copying searchtools... '", ")", ",", "nonl", "=", "True", ")", "if", "sphinx", ".", "version_info", "<", "(", "1", ",", "8", ")", ":", "search_js_file", "=", "'searchtools.js_t'", "else", ":", "search_js_file", "=", "'searchtools.js'", "path_src", "=", "os", ".", "path", ".", "join", "(", "package_dir", ",", "'themes'", ",", "'basic'", ",", "'static'", ",", "search_js_file", ")", "if", "os", ".", "path", ".", "exists", "(", "path_src", ")", ":", "path_dest", "=", "os", ".", "path", ".", "join", "(", "self", ".", "outdir", ",", "'_static'", ",", "'searchtools.js'", ")", "if", "renderer", "is", "None", ":", "# Sphinx 1.4 used the renderer from the existing builder, but", "# the pattern for Sphinx 1.5 is to pass in a renderer separate", "# from the builder. This supports both patterns for future", "# compatibility", "if", "sphinx", ".", "version_info", "<", "(", "1", ",", "5", ")", ":", "renderer", "=", "self", ".", "templates", "else", ":", "from", "sphinx", ".", "util", ".", "template", "import", "SphinxRenderer", "renderer", "=", "SphinxRenderer", "(", ")", "with", "codecs", ".", "open", "(", "path_src", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "h_src", ":", "with", "codecs", ".", "open", "(", "path_dest", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "h_dest", ":", "data", "=", "h_src", ".", "read", "(", ")", "data", "=", "self", ".", "REPLACEMENT_PATTERN", ".", "sub", "(", "self", ".", "REPLACEMENT_TEXT", ",", "data", ")", "h_dest", ".", "write", "(", "renderer", ".", "render_string", "(", "data", ",", "self", ".", "get_static_readthedocs_context", "(", ")", ")", ")", "else", ":", "log", ".", "warning", "(", "'Missing {}'", ".", "format", "(", "search_js_file", ")", ")", "log", ".", "info", "(", "'done'", ")" ]
Copy and patch searchtools This uses the included Sphinx version's searchtools, but patches it to remove automatic initialization. This is a fork of ``sphinx.util.fileutil.copy_asset``
[ "Copy", "and", "patch", "searchtools" ]
f1a01c51c675d36ac365162ea06814544c2aa410
https://github.com/rtfd/readthedocs-sphinx-ext/blob/f1a01c51c675d36ac365162ea06814544c2aa410/readthedocs_ext/readthedocs.py#L209-L247
train
Spirent/py-stcrestclient
stcrestclient/systeminfo.py
stc_system_info
def stc_system_info(stc_addr): """Return dictionary of STC and API information. If a session already exists, then use it to get STC information and avoid taking the time to start a new session. A session is necessary to get STC information. """ stc = stchttp.StcHttp(stc_addr) sessions = stc.sessions() if sessions: # If a session already exists, use it to get STC information. stc.join_session(sessions[0]) sys_info = stc.system_info() else: # Create a new session to get STC information. stc.new_session('anonymous') try: sys_info = stc.system_info() finally: # Make sure the temporary session in terminated. stc.end_session() return sys_info
python
def stc_system_info(stc_addr): """Return dictionary of STC and API information. If a session already exists, then use it to get STC information and avoid taking the time to start a new session. A session is necessary to get STC information. """ stc = stchttp.StcHttp(stc_addr) sessions = stc.sessions() if sessions: # If a session already exists, use it to get STC information. stc.join_session(sessions[0]) sys_info = stc.system_info() else: # Create a new session to get STC information. stc.new_session('anonymous') try: sys_info = stc.system_info() finally: # Make sure the temporary session in terminated. stc.end_session() return sys_info
[ "def", "stc_system_info", "(", "stc_addr", ")", ":", "stc", "=", "stchttp", ".", "StcHttp", "(", "stc_addr", ")", "sessions", "=", "stc", ".", "sessions", "(", ")", "if", "sessions", ":", "# If a session already exists, use it to get STC information.", "stc", ".", "join_session", "(", "sessions", "[", "0", "]", ")", "sys_info", "=", "stc", ".", "system_info", "(", ")", "else", ":", "# Create a new session to get STC information.", "stc", ".", "new_session", "(", "'anonymous'", ")", "try", ":", "sys_info", "=", "stc", ".", "system_info", "(", ")", "finally", ":", "# Make sure the temporary session in terminated.", "stc", ".", "end_session", "(", ")", "return", "sys_info" ]
Return dictionary of STC and API information. If a session already exists, then use it to get STC information and avoid taking the time to start a new session. A session is necessary to get STC information.
[ "Return", "dictionary", "of", "STC", "and", "API", "information", "." ]
80ee82bddf2fb2808f3da8ff2c80b7d588e165e8
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/systeminfo.py#L23-L46
train
Spirent/py-stcrestclient
stcrestclient/stchttp.py
StcHttp.new_session
def new_session(self, user_name=None, session_name=None, kill_existing=False, analytics=None): """Create a new test session. The test session is identified by the specified user_name and optional session_name parameters. If a session name is not specified, then the server will create one. Arguments: user_name -- User name part of session ID. session_name -- Session name part of session ID. kill_existing -- If there is an existing session, with the same session name and user name, then terminate it before creating a new session analytics -- Optional boolean value to disable or enable analytics for new session. None will use setting configured on server. Return: True is session started, False if session was already started. """ if self.started(): return False if not session_name or not session_name.strip(): session_name = '' if not user_name or not user_name.strip(): user_name = '' params = {'userid': user_name, 'sessionname': session_name} if analytics not in (None, ''): params['analytics'] = str(analytics).lower() try: status, data = self._rest.post_request('sessions', None, params) except resthttp.RestHttpError as e: if kill_existing and str(e).find('already exists') >= 0: self.end_session('kill', ' - '.join((session_name, user_name))) else: raise RuntimeError('failed to create session: ' + str(e)) # Starting session if self._dbg_print: print('===> starting session') status, data = self._rest.post_request('sessions', None, params) if self._dbg_print: print('===> OK, started') sid = data['session_id'] if self._dbg_print: print('===> session ID:', sid) print('===> URL:', self._rest.make_url('sessions', sid)) self._rest.add_header('X-STC-API-Session', sid) self._sid = sid return sid
python
def new_session(self, user_name=None, session_name=None, kill_existing=False, analytics=None): """Create a new test session. The test session is identified by the specified user_name and optional session_name parameters. If a session name is not specified, then the server will create one. Arguments: user_name -- User name part of session ID. session_name -- Session name part of session ID. kill_existing -- If there is an existing session, with the same session name and user name, then terminate it before creating a new session analytics -- Optional boolean value to disable or enable analytics for new session. None will use setting configured on server. Return: True is session started, False if session was already started. """ if self.started(): return False if not session_name or not session_name.strip(): session_name = '' if not user_name or not user_name.strip(): user_name = '' params = {'userid': user_name, 'sessionname': session_name} if analytics not in (None, ''): params['analytics'] = str(analytics).lower() try: status, data = self._rest.post_request('sessions', None, params) except resthttp.RestHttpError as e: if kill_existing and str(e).find('already exists') >= 0: self.end_session('kill', ' - '.join((session_name, user_name))) else: raise RuntimeError('failed to create session: ' + str(e)) # Starting session if self._dbg_print: print('===> starting session') status, data = self._rest.post_request('sessions', None, params) if self._dbg_print: print('===> OK, started') sid = data['session_id'] if self._dbg_print: print('===> session ID:', sid) print('===> URL:', self._rest.make_url('sessions', sid)) self._rest.add_header('X-STC-API-Session', sid) self._sid = sid return sid
[ "def", "new_session", "(", "self", ",", "user_name", "=", "None", ",", "session_name", "=", "None", ",", "kill_existing", "=", "False", ",", "analytics", "=", "None", ")", ":", "if", "self", ".", "started", "(", ")", ":", "return", "False", "if", "not", "session_name", "or", "not", "session_name", ".", "strip", "(", ")", ":", "session_name", "=", "''", "if", "not", "user_name", "or", "not", "user_name", ".", "strip", "(", ")", ":", "user_name", "=", "''", "params", "=", "{", "'userid'", ":", "user_name", ",", "'sessionname'", ":", "session_name", "}", "if", "analytics", "not", "in", "(", "None", ",", "''", ")", ":", "params", "[", "'analytics'", "]", "=", "str", "(", "analytics", ")", ".", "lower", "(", ")", "try", ":", "status", ",", "data", "=", "self", ".", "_rest", ".", "post_request", "(", "'sessions'", ",", "None", ",", "params", ")", "except", "resthttp", ".", "RestHttpError", "as", "e", ":", "if", "kill_existing", "and", "str", "(", "e", ")", ".", "find", "(", "'already exists'", ")", ">=", "0", ":", "self", ".", "end_session", "(", "'kill'", ",", "' - '", ".", "join", "(", "(", "session_name", ",", "user_name", ")", ")", ")", "else", ":", "raise", "RuntimeError", "(", "'failed to create session: '", "+", "str", "(", "e", ")", ")", "# Starting session", "if", "self", ".", "_dbg_print", ":", "print", "(", "'===> starting session'", ")", "status", ",", "data", "=", "self", ".", "_rest", ".", "post_request", "(", "'sessions'", ",", "None", ",", "params", ")", "if", "self", ".", "_dbg_print", ":", "print", "(", "'===> OK, started'", ")", "sid", "=", "data", "[", "'session_id'", "]", "if", "self", ".", "_dbg_print", ":", "print", "(", "'===> session ID:'", ",", "sid", ")", "print", "(", "'===> URL:'", ",", "self", ".", "_rest", ".", "make_url", "(", "'sessions'", ",", "sid", ")", ")", "self", ".", "_rest", ".", "add_header", "(", "'X-STC-API-Session'", ",", "sid", ")", "self", ".", "_sid", "=", "sid", "return", "sid" ]
Create a new test session. The test session is identified by the specified user_name and optional session_name parameters. If a session name is not specified, then the server will create one. Arguments: user_name -- User name part of session ID. session_name -- Session name part of session ID. kill_existing -- If there is an existing session, with the same session name and user name, then terminate it before creating a new session analytics -- Optional boolean value to disable or enable analytics for new session. None will use setting configured on server. Return: True is session started, False if session was already started.
[ "Create", "a", "new", "test", "session", "." ]
80ee82bddf2fb2808f3da8ff2c80b7d588e165e8
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/stchttp.py#L87-L140
train
Spirent/py-stcrestclient
stcrestclient/stchttp.py
StcHttp.join_session
def join_session(self, sid): """Attach to an existing session.""" self._rest.add_header('X-STC-API-Session', sid) self._sid = sid try: status, data = self._rest.get_request('objects', 'system1', ['version', 'name']) except resthttp.RestHttpError as e: self._rest.del_header('X-STC-API-Session') self._sid = None raise RuntimeError('failed to join session "%s": %s' % (sid, e)) return data['version']
python
def join_session(self, sid): """Attach to an existing session.""" self._rest.add_header('X-STC-API-Session', sid) self._sid = sid try: status, data = self._rest.get_request('objects', 'system1', ['version', 'name']) except resthttp.RestHttpError as e: self._rest.del_header('X-STC-API-Session') self._sid = None raise RuntimeError('failed to join session "%s": %s' % (sid, e)) return data['version']
[ "def", "join_session", "(", "self", ",", "sid", ")", ":", "self", ".", "_rest", ".", "add_header", "(", "'X-STC-API-Session'", ",", "sid", ")", "self", ".", "_sid", "=", "sid", "try", ":", "status", ",", "data", "=", "self", ".", "_rest", ".", "get_request", "(", "'objects'", ",", "'system1'", ",", "[", "'version'", ",", "'name'", "]", ")", "except", "resthttp", ".", "RestHttpError", "as", "e", ":", "self", ".", "_rest", ".", "del_header", "(", "'X-STC-API-Session'", ")", "self", ".", "_sid", "=", "None", "raise", "RuntimeError", "(", "'failed to join session \"%s\": %s'", "%", "(", "sid", ",", "e", ")", ")", "return", "data", "[", "'version'", "]" ]
Attach to an existing session.
[ "Attach", "to", "an", "existing", "session", "." ]
80ee82bddf2fb2808f3da8ff2c80b7d588e165e8
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/stchttp.py#L142-L154
train
Spirent/py-stcrestclient
stcrestclient/stchttp.py
StcHttp.end_session
def end_session(self, end_tcsession=True, sid=None): """End this test session. A session can be ended in three ways, depending on the value of the end_tcsession parameter: - end_tcsession=None: Stop using session locally, do not contact server. - end_tcsession=False: End client controller, but leave test session on server. - end_tcsession=True: End client controller and terminate test session (default). - end_tcsession='kill': Forcefully terminate test session. Specifying end_tcsession=False is useful to do before attaching an STC GUI or legacy automation script, so that there are not multiple controllers to interfere with each other. When the session is ended, it is no longer available. Clients should export any result or log files, that they want to preserve, before the session is ended. Arguments end_tcsession -- How to end the session (see above) sid -- ID of session to end. None to use current session. Return: True if session ended, false if session was not started. """ if not sid or sid == self._sid: if not self.started(): return False sid = self._sid self._sid = None self._rest.del_header('X-STC-API-Session') if end_tcsession is None: if self._dbg_print: print('===> detached from session') return True try: if end_tcsession: if self._dbg_print: print('===> deleting session:', sid) if end_tcsession == 'kill': status, data = self._rest.delete_request( 'sessions', sid, 'kill') else: status, data = self._rest.delete_request('sessions', sid) count = 0 while 1: time.sleep(5) if self._dbg_print: print('===> checking if session ended') ses_list = self.sessions() if not ses_list or sid not in ses_list: break count += 1 if count == 3: raise RuntimeError("test session has not stopped") if self._dbg_print: print('===> ok - deleted test session') else: # Ending client session is supported on version >= 2.1.5 if self._get_api_version() < (2, 1, 5): raise RuntimeError('option no available on server') status, data = self._rest.delete_request( 'sessions', sid, 'false') if self._dbg_print: print('===> OK - detached REST API from test session') except resthttp.RestHttpError as e: raise RuntimeError('failed to end session: ' + str(e)) return True
python
def end_session(self, end_tcsession=True, sid=None): """End this test session. A session can be ended in three ways, depending on the value of the end_tcsession parameter: - end_tcsession=None: Stop using session locally, do not contact server. - end_tcsession=False: End client controller, but leave test session on server. - end_tcsession=True: End client controller and terminate test session (default). - end_tcsession='kill': Forcefully terminate test session. Specifying end_tcsession=False is useful to do before attaching an STC GUI or legacy automation script, so that there are not multiple controllers to interfere with each other. When the session is ended, it is no longer available. Clients should export any result or log files, that they want to preserve, before the session is ended. Arguments end_tcsession -- How to end the session (see above) sid -- ID of session to end. None to use current session. Return: True if session ended, false if session was not started. """ if not sid or sid == self._sid: if not self.started(): return False sid = self._sid self._sid = None self._rest.del_header('X-STC-API-Session') if end_tcsession is None: if self._dbg_print: print('===> detached from session') return True try: if end_tcsession: if self._dbg_print: print('===> deleting session:', sid) if end_tcsession == 'kill': status, data = self._rest.delete_request( 'sessions', sid, 'kill') else: status, data = self._rest.delete_request('sessions', sid) count = 0 while 1: time.sleep(5) if self._dbg_print: print('===> checking if session ended') ses_list = self.sessions() if not ses_list or sid not in ses_list: break count += 1 if count == 3: raise RuntimeError("test session has not stopped") if self._dbg_print: print('===> ok - deleted test session') else: # Ending client session is supported on version >= 2.1.5 if self._get_api_version() < (2, 1, 5): raise RuntimeError('option no available on server') status, data = self._rest.delete_request( 'sessions', sid, 'false') if self._dbg_print: print('===> OK - detached REST API from test session') except resthttp.RestHttpError as e: raise RuntimeError('failed to end session: ' + str(e)) return True
[ "def", "end_session", "(", "self", ",", "end_tcsession", "=", "True", ",", "sid", "=", "None", ")", ":", "if", "not", "sid", "or", "sid", "==", "self", ".", "_sid", ":", "if", "not", "self", ".", "started", "(", ")", ":", "return", "False", "sid", "=", "self", ".", "_sid", "self", ".", "_sid", "=", "None", "self", ".", "_rest", ".", "del_header", "(", "'X-STC-API-Session'", ")", "if", "end_tcsession", "is", "None", ":", "if", "self", ".", "_dbg_print", ":", "print", "(", "'===> detached from session'", ")", "return", "True", "try", ":", "if", "end_tcsession", ":", "if", "self", ".", "_dbg_print", ":", "print", "(", "'===> deleting session:'", ",", "sid", ")", "if", "end_tcsession", "==", "'kill'", ":", "status", ",", "data", "=", "self", ".", "_rest", ".", "delete_request", "(", "'sessions'", ",", "sid", ",", "'kill'", ")", "else", ":", "status", ",", "data", "=", "self", ".", "_rest", ".", "delete_request", "(", "'sessions'", ",", "sid", ")", "count", "=", "0", "while", "1", ":", "time", ".", "sleep", "(", "5", ")", "if", "self", ".", "_dbg_print", ":", "print", "(", "'===> checking if session ended'", ")", "ses_list", "=", "self", ".", "sessions", "(", ")", "if", "not", "ses_list", "or", "sid", "not", "in", "ses_list", ":", "break", "count", "+=", "1", "if", "count", "==", "3", ":", "raise", "RuntimeError", "(", "\"test session has not stopped\"", ")", "if", "self", ".", "_dbg_print", ":", "print", "(", "'===> ok - deleted test session'", ")", "else", ":", "# Ending client session is supported on version >= 2.1.5", "if", "self", ".", "_get_api_version", "(", ")", "<", "(", "2", ",", "1", ",", "5", ")", ":", "raise", "RuntimeError", "(", "'option no available on server'", ")", "status", ",", "data", "=", "self", ".", "_rest", ".", "delete_request", "(", "'sessions'", ",", "sid", ",", "'false'", ")", "if", "self", ".", "_dbg_print", ":", "print", "(", "'===> OK - detached REST API from test session'", ")", "except", "resthttp", ".", "RestHttpError", "as", "e", ":", "raise", "RuntimeError", "(", "'failed to end session: '", "+", "str", "(", "e", ")", ")", "return", "True" ]
End this test session. A session can be ended in three ways, depending on the value of the end_tcsession parameter: - end_tcsession=None: Stop using session locally, do not contact server. - end_tcsession=False: End client controller, but leave test session on server. - end_tcsession=True: End client controller and terminate test session (default). - end_tcsession='kill': Forcefully terminate test session. Specifying end_tcsession=False is useful to do before attaching an STC GUI or legacy automation script, so that there are not multiple controllers to interfere with each other. When the session is ended, it is no longer available. Clients should export any result or log files, that they want to preserve, before the session is ended. Arguments end_tcsession -- How to end the session (see above) sid -- ID of session to end. None to use current session. Return: True if session ended, false if session was not started.
[ "End", "this", "test", "session", "." ]
80ee82bddf2fb2808f3da8ff2c80b7d588e165e8
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/stchttp.py#L156-L234
train
Spirent/py-stcrestclient
stcrestclient/stchttp.py
StcHttp.session_info
def session_info(self, session_id=None): """Get information on session. If session_id is None, the default, then return information about this session. If a session ID is given, then get information about that session. Arguments: session_id -- Id of session to get info for, if not this session. Return: Dictionary of session information. """ if not session_id: if not self.started(): return [] session_id = self._sid status, data = self._rest.get_request('sessions', session_id) return data
python
def session_info(self, session_id=None): """Get information on session. If session_id is None, the default, then return information about this session. If a session ID is given, then get information about that session. Arguments: session_id -- Id of session to get info for, if not this session. Return: Dictionary of session information. """ if not session_id: if not self.started(): return [] session_id = self._sid status, data = self._rest.get_request('sessions', session_id) return data
[ "def", "session_info", "(", "self", ",", "session_id", "=", "None", ")", ":", "if", "not", "session_id", ":", "if", "not", "self", ".", "started", "(", ")", ":", "return", "[", "]", "session_id", "=", "self", ".", "_sid", "status", ",", "data", "=", "self", ".", "_rest", ".", "get_request", "(", "'sessions'", ",", "session_id", ")", "return", "data" ]
Get information on session. If session_id is None, the default, then return information about this session. If a session ID is given, then get information about that session. Arguments: session_id -- Id of session to get info for, if not this session. Return: Dictionary of session information.
[ "Get", "information", "on", "session", "." ]
80ee82bddf2fb2808f3da8ff2c80b7d588e165e8
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/stchttp.py#L273-L292
train
Spirent/py-stcrestclient
stcrestclient/stchttp.py
StcHttp.files
def files(self): """Get list of files, for this session, on server.""" self._check_session() status, data = self._rest.get_request('files') return data
python
def files(self): """Get list of files, for this session, on server.""" self._check_session() status, data = self._rest.get_request('files') return data
[ "def", "files", "(", "self", ")", ":", "self", ".", "_check_session", "(", ")", "status", ",", "data", "=", "self", ".", "_rest", ".", "get_request", "(", "'files'", ")", "return", "data" ]
Get list of files, for this session, on server.
[ "Get", "list", "of", "files", "for", "this", "session", "on", "server", "." ]
80ee82bddf2fb2808f3da8ff2c80b7d588e165e8
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/stchttp.py#L294-L298
train
Spirent/py-stcrestclient
stcrestclient/stchttp.py
StcHttp.bll_version
def bll_version(self): """Get the BLL version this session is connected to. Return: Version string if session started. None if session not started. """ if not self.started(): return None status, data = self._rest.get_request('objects', 'system1', ['version', 'name']) return data['version']
python
def bll_version(self): """Get the BLL version this session is connected to. Return: Version string if session started. None if session not started. """ if not self.started(): return None status, data = self._rest.get_request('objects', 'system1', ['version', 'name']) return data['version']
[ "def", "bll_version", "(", "self", ")", ":", "if", "not", "self", ".", "started", "(", ")", ":", "return", "None", "status", ",", "data", "=", "self", ".", "_rest", ".", "get_request", "(", "'objects'", ",", "'system1'", ",", "[", "'version'", ",", "'name'", "]", ")", "return", "data", "[", "'version'", "]" ]
Get the BLL version this session is connected to. Return: Version string if session started. None if session not started.
[ "Get", "the", "BLL", "version", "this", "session", "is", "connected", "to", "." ]
80ee82bddf2fb2808f3da8ff2c80b7d588e165e8
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/stchttp.py#L309-L320
train
Spirent/py-stcrestclient
stcrestclient/stchttp.py
StcHttp.get
def get(self, handle, *args): """Returns the value(s) of one or more object attributes. If multiple arguments, this method returns a dictionary of argument names mapped to the value returned by each argument. If a single argument is given, then the response is a list of values for that argument. Arguments: handle -- Handle that identifies object to get info for. *args -- Zero or more attributes or relationships. Return: If multiple input arguments are given: {attrib_name:attrib_val, attrib_name:attrib_val, ..} If single input argument is given, then a single string value is returned. NOTE: If the string contains multiple substrings, then the client will need to parse these. """ self._check_session() status, data = self._rest.get_request('objects', str(handle), args) return data
python
def get(self, handle, *args): """Returns the value(s) of one or more object attributes. If multiple arguments, this method returns a dictionary of argument names mapped to the value returned by each argument. If a single argument is given, then the response is a list of values for that argument. Arguments: handle -- Handle that identifies object to get info for. *args -- Zero or more attributes or relationships. Return: If multiple input arguments are given: {attrib_name:attrib_val, attrib_name:attrib_val, ..} If single input argument is given, then a single string value is returned. NOTE: If the string contains multiple substrings, then the client will need to parse these. """ self._check_session() status, data = self._rest.get_request('objects', str(handle), args) return data
[ "def", "get", "(", "self", ",", "handle", ",", "*", "args", ")", ":", "self", ".", "_check_session", "(", ")", "status", ",", "data", "=", "self", ".", "_rest", ".", "get_request", "(", "'objects'", ",", "str", "(", "handle", ")", ",", "args", ")", "return", "data" ]
Returns the value(s) of one or more object attributes. If multiple arguments, this method returns a dictionary of argument names mapped to the value returned by each argument. If a single argument is given, then the response is a list of values for that argument. Arguments: handle -- Handle that identifies object to get info for. *args -- Zero or more attributes or relationships. Return: If multiple input arguments are given: {attrib_name:attrib_val, attrib_name:attrib_val, ..} If single input argument is given, then a single string value is returned. NOTE: If the string contains multiple substrings, then the client will need to parse these.
[ "Returns", "the", "value", "(", "s", ")", "of", "one", "or", "more", "object", "attributes", "." ]
80ee82bddf2fb2808f3da8ff2c80b7d588e165e8
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/stchttp.py#L336-L360
train
Spirent/py-stcrestclient
stcrestclient/stchttp.py
StcHttp.create
def create(self, object_type, under=None, attributes=None, **kwattrs): """Create a new automation object. Arguments: object_type -- Type of object to create. under -- Handle of the parent of the new object. attributes -- Dictionary of attributes (name-value pairs). kwattrs -- Optional keyword attributes (name=value pairs). Return: Handle of newly created object. """ data = self.createx(object_type, under, attributes, **kwattrs) return data['handle']
python
def create(self, object_type, under=None, attributes=None, **kwattrs): """Create a new automation object. Arguments: object_type -- Type of object to create. under -- Handle of the parent of the new object. attributes -- Dictionary of attributes (name-value pairs). kwattrs -- Optional keyword attributes (name=value pairs). Return: Handle of newly created object. """ data = self.createx(object_type, under, attributes, **kwattrs) return data['handle']
[ "def", "create", "(", "self", ",", "object_type", ",", "under", "=", "None", ",", "attributes", "=", "None", ",", "*", "*", "kwattrs", ")", ":", "data", "=", "self", ".", "createx", "(", "object_type", ",", "under", ",", "attributes", ",", "*", "*", "kwattrs", ")", "return", "data", "[", "'handle'", "]" ]
Create a new automation object. Arguments: object_type -- Type of object to create. under -- Handle of the parent of the new object. attributes -- Dictionary of attributes (name-value pairs). kwattrs -- Optional keyword attributes (name=value pairs). Return: Handle of newly created object.
[ "Create", "a", "new", "automation", "object", "." ]
80ee82bddf2fb2808f3da8ff2c80b7d588e165e8
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/stchttp.py#L362-L376
train